问题描述
我正在处理一段代码,该代码使用其自己的处理程序和格式实例化其自己的记录器.
I am working on a piece of code which instantiates its own logger with its own handlers and format.
现在,我添加了一个直接使用日志记录模块的库,它使我的记录器搞砸了-原始记录器开始以不同的格式打印每行两次,而默认记录器什么也不打印.
Now I've added a use of a library which uses the logging module directly and it screws up my logger - The original logger starts printing each line twice in different formats while the default logger prints nothing at all.
有什么建议吗?MCVE:
Any suggestions?MCVE:
import sys
import logging
log = logging.getLogger('foo')
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)
log.info("works once")
logging.info("Isn't printed")
log.info("printed twice with different format")
输出:
works once
printed twice with different format
INFO:foo:printed twice with different format
似乎也不是默认记录器以某种方式向我的记录器实例添加了额外的处理程序:
It also doesnt seem like the default logger somehow adds an extra handler to my logger instance:
> print log.handlers
[<logging.StreamHandler object at 0x7f5d14314990>]
我无法更改包含的模块...
I can't change the module I've included...
推荐答案
在挖掘和挖掘之后,我终于找到了一些文档来救了我!
After digging and digging, I finally found the bit of documentation that saved me!
如果此结果为true,则事件记录到此 记录器将传递给更高级别的处理程序(祖先) 记录器,以及与此记录器相连的所有处理程序.留言内容 直接传递给祖先记录程序的处理程序- 级别或相关祖先记录器的过滤器都不会考虑.
If this evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.
如果结果为假,则日志消息不会传递到 祖先记录器的处理程序.
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
构造函数将此属性设置为True.
The constructor sets this attribute to True.
设置log.propagate = False
结束了我的不幸.
通过logging.info
第一次使用默认记录器似乎已经初始化了默认记录器,从那一刻起,传播开始起作用.
It would appear that the 1st use of the default logger through logging.info
has initialized the default logger and from that moment the propagation started having an effect.
这篇关于使用默认记录器后,Python 2记录器重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!