【发布时间】:2021-09-03 11:38:47
【问题描述】:
问题:当我调用 logging.basicConfig 除了配置我自己的记录器,我得到重复的日志
- 我正在运行 python 3.6.8
- 简单的解决方法是不调用 logging.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
【问题讨论】: