What is the advantage of having a logger object instead of using logging?

蓝咒 提交于 2020-12-09 07:21:13

问题


With Python and the logging library, you can configure logging via a dict log_config and

logging.config.dictConfig(log_config)

The you can log via logging.info or create a logger object and use that. What is the advantage of having a logger object?


回答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...



来源:https://stackoverflow.com/questions/48185953/what-is-the-advantage-of-having-a-logger-object-instead-of-using-logging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!