Python日志记录模块多次打印行 [英] Python logging module is printing lines multiple times

查看:402
本文介绍了Python日志记录模块多次打印行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import logging
class A(object):
    def __init__(self):
        self._l = self._get_logger()

    def _get_logger(self):
        loglevel = logging.INFO
        l = logging.getLogger(__name__)
        l.setLevel(logging.INFO)
        h = logging.StreamHandler()
        f = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        h.setFormatter(f)
        l.addHandler(h)
        l.setLevel(loglevel)
        return l  

    def p(self, msg):
        self._l.info(msg)

for msg in ["hey", "there"]:
    a = A()
    a.p(msg)

我得到的输出是:

2013-07-19 17:42:02,657 INFO hey
2013-07-19 17:42:02,657 INFO there
2013-07-19 17:42:02,657 INFO there

为什么有"被打印两次?同样,如果我在循环中添加另一个类A的对象并打印一条消息,它将被打印三次.

Why is "there" being printed twice? Similarly, if I add another object of class A inside the loop and print a message, it gets printed thrice.

文档说,如果记录器的名称匹配,logging.getLogger()将始终返回记录器的相同实例.在这种情况下,名称确实匹配.它不应该返回相同的记录器实例吗?如果确实如此,为什么该消息会多次打印?

The documentation says that logging.getLogger() will always return the same instance of the logger if the name of the logger matches. In this case, the name does match. Should it not return the same logger instance? If it is infact doing so, why is the message getting printed multiple times?

推荐答案

记录器创建一次,但创建多个处理程序.

logger is created once, but multiple handlers are created.

创建一次A.

a = A()
for msg in ["hey", "there"]:
    a.p(msg)

或如下更改_get_logger:

def _get_logger(self):
    loglevel = logging.INFO
    l = logging.getLogger(__name__)
    if not getattr(l, 'handler_set', None):
        l.setLevel(loglevel)
        h = logging.StreamHandler()
        f = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        h.setFormatter(f)
        l.addHandler(h)
        l.setLevel(loglevel)
        l.handler_set = True
    return l  

更新

从Python 3.2开始,您可以使用 logging.Logger.hasHandlers 查看此记录器是否配置了任何处理程序. (感谢@toom)

Since Python 3.2, you can use logging.Logger.hasHandlers to see if this logger has any handlers configured. (thanks @toom)

def _get_logger(self):
    loglevel = logging.INFO
    l = logging.getLogger(__name__)
    if not l.hasHandlers():
        ...
    return l

这篇关于Python日志记录模块多次打印行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆