使用登录多个模块 [英] Using logging in multiple modules

查看:60
本文介绍了使用登录多个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的小型python项目-

I have a small python project that has the following structure -

Project 
 -- pkg01
   -- test01.py
 -- pkg02
   -- test02.py
 -- logging.conf

我计划使用默认的日志记录模块将消息打印到stdout和日志文件. 要使用日志记录模块,需要进行一些初始化-

I plan to use the default logging module to print messages to stdout and a log file. To use the logging module, some initialization is required -

import logging.config

logging.config.fileConfig('logging.conf')
logger = logging.getLogger('pyApp')

logger.info('testing')

目前,在开始记录消息之前,我会在每个模块中执行此初始化.是否可以只在一个地方执行一次初始化,以便通过记录整个项目来重复使用相同的设置?

At present, I perform this initialization in every module before I start logging messages. Is it possible to perform this initialization only once in one place such that the same settings are reused by logging all over the project?

推荐答案

在每个模块中,最佳做法是定义一个记录器,如下所示:

Best practice is, in each module, to have a logger defined like this:

import logging
logger = logging.getLogger(__name__)

在模块顶部附近,然后在模块中的其他代码中执行

near the top of the module, and then in other code in the module do e.g.

logger.debug('My message with %s', 'variable data')

如果您需要在模块内细分日志记录活动,请使用例如

If you need to subdivide logging activity inside a module, use e.g.

loggerA = logging.getLogger(__name__ + '.A')
loggerB = logging.getLogger(__name__ + '.B')

,并根据需要登录到loggerAloggerB.

and log to loggerA and loggerB as appropriate.

在您的一个或多个主程序中,例如:

In your main program or programs, do e.g.:

def main():
    "your program code"

if __name__ == '__main__':
    import logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    main()

def main():
    import logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    # your program code

if __name__ == '__main__':
    main()

有关从多个模块进行日志记录的信息,请参见此处,以及

See here for logging from multiple modules, and here for logging configuration for code which will be used as a library module by other code.

更新:调用fileConfig()时,如果您使用的是Python 2.6或更高版本,则可能要指定disable_existing_loggers=False(请参阅

Update: When calling fileConfig(), you may want to specify disable_existing_loggers=False if you're using Python 2.6 or later (see the docs for more information). The default value is True for backward compatibility, which causes all existing loggers to be disabled by fileConfig() unless they or their ancestor are explicitly named in the configuration. With the value set to False, existing loggers are left alone. If using Python 2.7/Python 3.2 or later, you may wish to consider the dictConfig() API which is better than fileConfig() as it gives more control over the configuration.

这篇关于使用登录多个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆