Python日志记录-日志记录数量错误

2024-04-18 00:35:39 发布

您现在位置: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

E一切正常,创建日志文件并在屏幕上打印日志,但为什么任务2和任务3有多条记录


Tags: runpyimportselflogosloggingdef
1条回答
网友
1楼 · 发布于 2024-04-18 00:35:39

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

FWIW您的整个MyLog类是一个非常糟糕的主意-实际上是一个反模式。使用记录器的代码(我们称之为“库代码”)不应该以任何方式配置记录器-只需要请求它们(使用logging.getLogger(<name>)并使用它们,配置应该由应用程序的入口点来处理

相关问题 更多 >

    热门问题