Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.38k stars 690 forks source link

Issue with custom log levels and Rich handlers in loguru #1171

Open ryan-umbra opened 1 month ago

ryan-umbra commented 1 month ago

Hey there, I am running into (what I am pretty sure is) a bug when adding a custom log level and using Rich logging. For some reason when I add a custom log level in loguru with logger.add(...), and have show_levels=True in my RichHandler, the levels appear as "Level X" - where "X" is the value of the custom level - instead of the level name (see attached). The bummer about this is if I am able to have show_levels=True, then Rich automatically pads the levels, and gives them color. The simplest way to reproduce this bug:

from loguru import logger
from rich import RichHandler

logger.remove(0)

# Add custom level "TEST"
logger.level("TEST", no=15, color="<cyan>")

# Create and add RichHandler object
rich = RichHandler(
    ...
    show_level=True
)
format = "{message}"
logger.add(rich, format=format, level=level)

My workaround to this is to have show_levels=False in my RichHandler then include level in my loguru format with "{level} {message}". I know I can pad the level which is nice, but it won't color them even if I do "<level>{level}</level>" unfortunately.

I have looked through a lot of issue pages and not seen one that matches this issue. The closes was this post and while the issue is similar, the problem seems quite different especially since they are not using Rich.

I have tried a few other workarounds too. What I discussed here I think is the clearest semblance of a bug and simplest (yet not ideal) workaround. Any help with this is greatly appreciated!

I am using loguru 0.7.2 and rich 12.6.0

BadLogLevel

Delgan commented 1 month ago

Hey @ryan-umbra.

I think your issue is similar to https://github.com/Delgan/loguru/issues/1149.

Basically, rich uses standard logging levels and isn't aware of the Loguru ones. Therefore, you need to register your TEST level with logging.addLevelName():

logging.addLevelName(15, "TEST")