我的目标是从多个模块记录日志,同时只在主程序中配置记录器。如this answer所示,应该包含。
在主程序中,然后在所有其他模块中包括。
我期望的是,当在 c.py 中执行
logging.config.fileConfig('/path/to/logging.conf')
在主程序中,然后在所有其他模块中包括。
logger = logging.getLogger(__name__)
我相信这就是我下面所做的,但我得到了意外的行为。
c.py
# c.py
import logging
import logging.config
import d
logging.config.fileConfig("logging.conf")
logger = logging.getLogger(__name__)
logger.warning('logging from c')
d.foo()
d.py
# d.py
import logging
logger = logging.getLogger(__name__)
# this will print when d is imported
logger.warning('logging from d on import')
def foo():
# this does not print
logger.warning("logging from d on call foo()")
输出
$ python c.py
logging from d on import
logging from c
我期望的是,当在 c.py 中执行
d.foo()
时,会从d
记录一条消息,但事实并非如此。这很令人困惑,因为当在d
模块级别调用记录器时,它会将消息记录到控制台,但是当从foo()
内部调用时却没有记录。
配置文件
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(message)s
datefmt=
进一步分析
我注意到,如果我删除这行代码
logging.config.fileConfig("logging.conf")
从c.py
,然后从d.foo()
记录日志按预期工作。因此,要么配置文件中有问题,要么由于我提供了配置文件,导致d.py
中的记录器出现问题。
问题
- 为什么在模块级别调用时会从
d
记录消息,但不会从d.foo()
内部记录? - 如何实现从多个模块记录日志的目标,同时只在主程序中配置日志记录?