logging.config.fileConfig('/path/to/logging.conf')
在主程序中,然后在所有其他模块中包括
logger = logging.getLogger(__name__)
我相信这就是我在下面所做的,但我得到了意想不到的行为.
c.py
# c.pyimport loggingimport logging.configimport dlogging.config.fileConfig("logging.conf")logger = logging.getLogger(__name__)logger.warning('logging from c')d.foo()
d.py
# d.pyimport logginglogger = logging.getLogger(__name__)# this will print when d is importedlogger.warning('logging from d on import')def foo(): # this does not print logger.warning("logging from d on call foo()")
产量
$python c.pylogging from d on importlogging from c
我除了之外,是当d.foo()在c.py中执行时,将从d记录消息,但事实并非如此.这很令人困惑,因为当从d中的模块级别调用记录器时,它会将一条消息记录到控制台,但是当从foo()内部调用时它不会.
配置文件
[loggers]keys=root[handlers]keys=consoleHandler[formatters]keys=simpleFormatter[logger_root]level=DEBUGhandlers=consoleHandler[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(message)sdatefmt=
更深入的分析
所以我注意到,如果我删除该行
logging.config.fileConfig("logging.conf")
从c.py开始,然后从d.foo()进行日志记录按预期工作.所以在配置文件中有一些错误,或者由于我提供的配置文件导致d.py中的记录器搞砸了.
题
>为什么从模块级别调用时会从d记录消息,而不是从d.foo()内部调用?
>如何才能实现从多个模块进行日志记录的目标,同时仅在主程序中配置日志记录?
import d
来之前
logging.config.fileConfig("logging.conf")
正如@davIDejones所指出的那样.原因如下:
如docs中所述,当调用logging.config.fileConfig()时,其默认行为是禁用任何现有记录器.因此,当导入d发生时,logger在d中初始化,然后当调用logging.config.fileConfig()时,d中的记录器被禁用,这就是为什么我们在调用d.foo()时没有看到任何记录.
解
logging.config.fileConfig()接受一个参数disable_existing_loggers,默认为True.使用
logging.config.fileConfig("logging.conf",disable_existing_loggers=False)
输出变成了
>>> python c.pylogging from d on importlogging from clogging from d on call foo()
正如所料.
总结以上是内存溢出为你收集整理的Python记录多个模块记录器不在主程序外工作全部内容,希望文章能够帮你解决Python记录多个模块记录器不在主程序外工作所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)