Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.62k stars 695 forks source link

Modified Internal log level cache for better interoperability #1106

Open misotrnka opened 6 months ago

misotrnka commented 6 months ago

In my work I've come accross situations, where a third-party package is using my Loguru logger to emit logs. I've noticed that many time these messages are formated (colored) differently from messages emited in my code. After a brief investigation it turned out the third-party package is calling the log() method like this:

self.logger.log(logging.INFO, message)

The logging.INFO variable is an integer constant 20. However, Loguru's Logger._log() method expects a string, such as "INFO". Not finding the integer 20 in the internal core.levels_lookup cache results into a different formatting of the message:

image

(The first message is logged through the third-party package, while the second is logged natively in my code)

It is not possible to solve this using a custom log filter, because in Loguru the log level is resolved internally and the LogRecord.levels information is not used.

I believe passing the log level using the logging package's enum is a good and wide-spread practice and should be supported by Loguru.

I propose a simple solution: adding integer keys in additon to string keys to the internal log level cache. This effectivelly resolves the issue, increasing Loguru's interoperability with other packages without any modifications the the internal processing flow and logic.

Delgan commented 6 months ago

Thanks for the suggestion @misotrnka.

However, as you can see with failing tests, the observed behavior is actually the expected one. See notably #599, #1011, #1054.

Using Loguru, levels are uniquely identified by their name, not by their severity. This is because multiple levels can share the same severity, and it would lead to ambiguities when trying to map the severity to the appropriate name. Consequently, when an integer is used instead of a name, Loguru interprets it as an "anonymous level", and formats it as such.

Basically, it means the users of your library should use "INFO" instead of logging.INFO, since this is the expected usage of Loguru.