是什么导致日志记录模块多次记录一条记录? [英] What could cause the logging module to log a record multiple times?
问题描述
我有一个多线程Python应用程序,它使用了内置于日志记录中模块.为了控制日志记录级别并使以后更容易将StreamHandler
与FileHandler
交换,我创建了一个通用的辅助函数,每个模块都调用该函数来创建相同的记录器(名称除外).
I have a multi-threaded Python application that makes use of the built in logging module. To control the logging levels and make it easier to swap the StreamHandler
with a FileHandler
in the future, I have created a common helper function called by each module to create an identical logger (other than its name).
如何解决此问题?
关键点
- 项目中的每个模块都有其自己的记录器实例.
- 示例输出是通过一次调用记录器(
self._logger.info("Logger Setup")
) 生成的
- 我尝试包括当前线程名称(
threading.Thread.getName()
),它可以确认同一线程正在调用,从而导致多个日志.
- Each module in the project has its own logger instance.
- The sample output is generated by a single call to a logger (
self._logger.info("Logger Setup")
) - I have tried including the current thread name (
threading.Thread.getName()
) and it confirms that the same thread is calling causing the multiple logs.
创建记录器-现在可以使用
import logging
import sys
def createSystemLogHandler(logger):
# This is now called once at the logger's root
ch = logging.StreamHandler(sys.stdout) # Normal output is to stderr which doesn't show up on Window's CMD
format = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
ch.setFormatter(format)
logger.addHandler(ch)
return logger
def configureSystemLogger(name='', level=logging.WARNING):
logger = logging.getLogger(name)
logger.setLevel(level)
logger.info("Logger Setup")
return logger
示例输出
2012-04-25 21:59:40,720 - INFO - HW_MGR - Logger Setup
2012-04-25 21:59:40,720 - INFO - HW_MGR - Logger Setup
2012-04-25 21:59:40,720 - INFO - HW_MGR - Logger Setup
2012-04-25 21:59:40,720 - INFO - HW_MGR - Logger Setup
2012-04-25 21:59:40,720 - INFO - HW_MGR - Logger Setup
推荐答案
我的猜测是您有多个处理程序(即,一条消息被多次发出;但是在重新阅读您的问题时,看起来像您已经知道).要调试,请尝试:
My guess is that you've got multiple handlers (ie, one message is being emitted multiple times; but on re-reading your question, it looks like you already knew that). To debug that, try:
- 查看
logging.getLogger("").handlers
(即根记录器上的处理程序) - 检查您对
addHandler()
的呼叫
- 布兰登·罗德(Brandon Rhode)
pdb
来跟踪日志消息的生命周期(即,放置一个断点)恰好在调用self._logger.info(…)
之前,然后进入该函数).
- Looking at
logging.getLogger("").handlers
(ie, the handlers on the root logger) - Checking your calls to
addHandler()
- Brandon Rhode's
logging_tree
module - Use
pdb
to trace a log message's lifecycle (ie, put a breakpoint just before a call toself._logger.info(…)
, then step into that function).
这篇关于是什么导致日志记录模块多次记录一条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!