我有以下代码:
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 类对象并打印一条消息,它会被打印三次。
文档说,如果记录器的名称匹配,logging.getLogger() 将始终返回相同的记录器实例。在这种情况下,名称确实匹配。它不应该返回相同的记录器实例吗?如果确实这样做了,为什么会多次打印该消息?