我正在使用 Python 日志记录,由于某种原因,我的所有消息都出现了两次。
我有一个模块来配置日志记录:
# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
self.logger = logging.getLogger("my_logger")
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = 0
# Format for our loglines
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# Setup console logging
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
# Setup file logging as well
fh = logging.FileHandler(LOG_FILENAME)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
self.logger.addHandler(fh)
后来,我调用这个方法来配置日志:
if __name__ == '__main__':
tom = Boy()
tom.configure_logging(LOG_FILENAME)
tom.buy_ham()
然后在里面说,buy_ham 模块,我会调用:
self.logger.info('Successfully able to write to %s' % path)
由于某种原因,所有消息都出现了两次。我注释掉了一个流处理程序,还是一样的。有点奇怪,不知道为什么会这样……哈哈。假设我错过了一些明显的东西。
干杯, 维克多
最佳答案
您正在调用 configure_logging
两次(可能在 Boy
的 __init__
方法中):getLogger
将返回相同的对象,但 addHandler
不检查是否已将类似的处理程序添加到记录器。
尝试跟踪对该方法的调用并消除其中一个。或者在 Boy
的 __init__
方法中设置一个标志 logging_initialized
初始化为 False
并更改 configure_logging
如果 logging_initialized
为 True
则不执行任何操作,并在初始化记录器后将其设置为 True
。
如果您的程序创建了多个 Boy
实例,则您必须通过添加处理程序的全局 configure_logging
函数和 Boy.configure_logging
方法只初始化 self.logger
属性。
解决此问题的另一种方法是检查记录器的 handlers 属性:
logger = logging.getLogger('my_logger')
if not logger.handlers:
# create the handlers and call logger.addHandler(logging_handler)
关于python - 使用 Python 日志记录出现两次的日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729268/