如何让模块使用__main__文件中的记录器(及其配置)?

时间:2017-04-26 03:33:05

标签: python python-3.x logging

如何让auxiliary_module.py中的记录器记录到main.py中的记录器? 以下示例是Python's documentation的改编。

假设模型结构如:

module
 |---main.py
 |---auxiliary_module.py

文件main.py如下所示:

import logging
import auxiliary_module

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)
logger.addHandler(ch)

logger.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
logger.info('created an instance of auxiliary_module.Auxiliary')
logger.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
logger.info('finished auxiliary_module.Auxiliary.do_something')

auxiliary_module.py看起来像这样:

import logging

module_logger = logging.getLogger(__name__)

class Auxiliary:
    def __init__(self):
        self.logger = logging.getLogger(__name__+'.Auxiliary')
        self.logger.info('creating an instance of Auxiliary')

    def do_something(self):
        self.logger.info('doing something')
        a = 1 + 1
        self.logger.info('done doing something')

这是运行main.py(创建类实例并调用方法)后日志的样子:

2017-04-26 13:22:00,897 - __main__ - INFO - creating an instance of auxiliary_module.Auxiliary
2017-04-26 13:22:00,897 - __main__ - INFO - created an instance of auxiliary_module.Auxiliary
2017-04-26 13:22:00,897 - __main__ - INFO - calling auxiliary_module.Auxiliary.do_something
2017-04-26 13:22:00,897 - __main__ - INFO - finished auxiliary_module.Auxiliary.do_something

如何配置auxiliary_module.py以在main.py中使用记录器?也就是说,如果main.py中的记录器配置为使用certail格式和处理程序,那么如何让auxiliary_module.py使用相同的配置?

1 个答案:

答案 0 :(得分:1)

您可以简单地为两个模块使用的logging.getLogger()命名,例如logger = logging.getLogger('my-logger')