宝玛科技网
您的当前位置:首页python日志打印两次_Python日志模块正在多次打印行

python日志打印两次_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的对象并打印消息,那么它将被打印三次。

文档中说,如果记录器的名称匹配,logging.getLogger()将始终返回记录器的同一实例。在本例中,名称确实匹配。它不应该返回同一个记录器实例吗?如果它确实这样做了,为什么信息会被多次打印?

因篇幅问题不能全部显示,请点此查看更多更全内容