python logging - 日志记录数量错误

时间:2018-05-28 09:04:46

标签: python

我定义了一个日志类,目的是记录日志并同时打印到屏幕,这里是我的日志类文件(utils / mylog.py):

import logging
import os
import time

class MyLog(object):
    def __init__(self):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.DEBUG)
        self.logfile = os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) + '\logs\\' + time.strftime('%Y-%m-%d',time.localtime()) + '.log'
        self.formatter = logging.Formatter('%(asctime)-12s %(filename)s[line:%(lineno)d] %(name)-10s %(levelname)s %(message)s')

        self.loghand = logging.FileHandler(self.logfile)
        self.loghand.setFormatter(self.formatter)
        self.loghand.setLevel(logging.DEBUG)
        self.loghandst = logging.StreamHandler()
        self.loghandst.setFormatter(self.formatter)
        self.logger.addHandler(self.loghand)
        self.logger.addHandler(self.loghandst)

    def debug(self,msg):
        self.logger.debug(msg)

    def info(self,msg):
        self.logger.info(msg)

    def warning(self,msg):
        self.logger.info(msg)

    def error(self,msg):
        self.logger.error(msg)

    def critical(self,msg):
        self.logger.critical(msg) 

这是同一目录(utils / testlog.py)中的测试文件:

from utils.mylog import MyLog

class TestA():
    def __init__(self):
        self.log = MyLog()

    def run(self,a,b):
        self.log.debug('calc a + b:%d + %d' %(a,b))
        return a + b

class TestB():
    def __init__(self):
        self.log = MyLog()

    def run(self,a,b):
        self.log.warning('second calc a + b:%d + %d' %(a,b))
        return a + b + 6

class TestC():
    def __init__(self):
        self.log = MyLog()

    def run(self,a,b):
        self.log.critical('third calc a + b:%d + %d' %(a,b))
        return a + b + 6


if __name__ == '__main__':

    task1 = TestA()
    task1.run(12,56)
    task2 = TestB()
    task2.run(10, 56)
    task3 = TestC()
    task3.run(77,88)

结果:

2018-05-28 16:49:08,992 mylog.py[line:27] root       DEBUG calc a + b:12 + 56
2018-05-28 16:49:08,997 mylog.py[line:33] root       INFO second calc a + b:10 + 56
2018-05-28 16:49:08,997 mylog.py[line:33] root       INFO second calc a + b:10 + 56
2018-05-28 16:49:08,997 mylog.py[line:39] root       CRITICAL third calc a + b:77 + 88
2018-05-28 16:49:08,997 mylog.py[line:39] root       CRITICAL third calc a + b:77 + 88
2018-05-28 16:49:08,997 mylog.py[line:39] root       CRITICAL third calc a + b:77 + 88

ereything运行良好,创建日志文件并在屏幕上打印日志,但为什么任务2和任务3有多个记录?

1 个答案:

答案 0 :(得分:0)

logging.getLogger()始终返回相同的记录器(在本例中为根记录器),因此每次实例化新的MyLog实例时,都会继续向根记录器添加处理程序。

FWIW你的整个MyLog课程是一个非常糟糕的主意 - 实际上是反模式。代码使用记录器(我们称之为“库代码”)不应该以任何方式配置记录器 - 仅询问​​它们(使用logging.getLogger(<name>)并使用它们,并且应该处理配置按应用程序的入口点。