Python 2 logger repeats lines after use of default logger

百般思念 提交于 2020-01-06 06:52:22

问题


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.

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")

Output:

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...


回答1:


After digging and digging, I finally found the bit of documentation that saved me!

Logger.propagate

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.

The constructor sets this attribute to True.

Setting log.propagate = False ended my misfortune.

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.



来源:https://stackoverflow.com/questions/47440034/python-2-logger-repeats-lines-after-use-of-default-logger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!