What Is The Advantage Of Having A Logger Object Instead Of Using Logging?
Solution 1:
Loggers form a hierarchy based on their names (using "dotted.path" notation), with the root logger on top. The canonical ways to create loggers is to have one per module, named from the module's __name__
attribute so if you have a package named "mylib" with modules "utils", "core" and "api", you'll have loggers "mylib", "mylib.utils", "mylib.core" and "mylib.api", where the three last ones are children of "mylib" (which is of course a child of the root logger).
From this you can configure either only the root logger, or more specifically configure the "mylib" logger, or even more specifically configure ie "mylib.api" (note that by default loggers do propagate to their parents). If instead you only use logging
directly in all your package, you won't be able to customize child loggers per package/module.
The point here is that loggers calls should be decoupled from loggers configuration - library code defines and calls loggers, configuration is the duty of the app using the libraries. The reason is, obviously, that the library author cannot know which apps will use the library code nor how the app's author wants his loggers to be configured. This system gives the app's author (or the sysadmin or whoever is in charge of configuring/deploying the app) full, fine-grained control over logger's configuration. If all your library code only use the root logger then the app author/admin/user cannot have different settings per library/module, and (s)he will hate you for being so intrusive (and let's not talk about how (s)he will feel if your library tries to actually mess with the loggers configuration in any way).
To make a long story short: stick to the sane conventions, use logger = logging.getLogger(__name__)
in your modules, do not try to configure logging in your library code, and your library users will be happy.
EDIT : as you mention in a comment, declaring loggers at the module level can cause problems if the app configures the logging after importing your lib and does not set disable_existing_loggers
to False. As far as I'm concerned it's the app's author responsability to either configure logging before import anything else and/or to set disable_existing_loggers
to False. Configuring the logging first is IMHO a good idea anyway since it will allow library code to log eventual issues at import time...
Post a Comment for "What Is The Advantage Of Having A Logger Object Instead Of Using Logging?"