调用logging.basicConfig时重复日志



问题:当我调用日志记录时。basicConfig除了配置我自己的日志记录器之外,我还得到了重复的日志

  • 我正在运行python 3.6.8
  • 简单的解决方法是不使用呼叫记录。basicConfig -然而,我正在导入调用它的模块
  • 我不明白为什么日志要被复制。我已经检查了日志记录器上的处理程序的数量,只有一个处理程序

重现问题的代码

import logging
import sys
# create a logger, add a handler and a formatter
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s"))
log.addHandler(handler)
# call basicConfig
logging.basicConfig(level=logging.INFO) # logs not duplicated if this line is removed
# create a log message
log.info("hello world")
# verify the number of handlers on the logger
print(f" num_handlers = {len(log.handlers)}")
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#INFO:__main__:hello world
#INFO:__main__:hello world
#num_handlers = 1

Python日志记录器存在于层次结构中。有一个根记录器(可通过root = logging.getLogger()访问),它始终位于层次结构的根/顶部,并在调用basicConfig时进行配置。其他每个记录器都在层次结构中传播它们的日志,因此每个日志最终都会到达根记录器(更确切地说:根记录器处理程序)。

一个可能的解决方案是停止记录器传播:

log = logging.getLogger(__name__)
log.propagate = False

相关内容

最新更新