我的日志记录类上的奇怪行为

时间:2013-08-08 03:47:57

标签: python oop logging

我会尽量恢复。我写了这堂课:

记录类

import logging, logging.handlers.TimedRotatingFileHandler

class Logger(object):
    def __init__(self, log_filename):
        logging.basicConfig(format='%(asctime)s %(message)s')
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        loghandler = TimedRotatingFileHandler(
            log_filename, when="midnight", backupCount=50
        )
        loghandler.setFormatter(formatter)
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(loghandler)

    def getLogger(self):
        return self.logger

确实很好用,现在问题出现了,当我有一个使用Logger实例的脚本时,在该脚本中我实例化了一个使用Logger的类,如下所示:

脚本

import ClassA

A = ClassA()
log = Logger(log_filename='script_logger.log')
logger = log.getLogger()
logger.info('Initiated Script')

while True:
    logger.info('Looping')
    A.run()

我班上的样子:

ClassA模块

class ClassA(object):
    def __init__(self):
        log = Logger(log_filename='class_logger.log')
        self.logger = log.getLogger()
        self.logger.info('Started ClassA')

    def run(self):
        self.logger.info('Into method run')

现在我希望有两个单独的日志文件,class_logger.logscript_logger.log可以正常工作,但这两个文件的内容完全相同。

因此script_logger.logclass_logger.log具有以下内容:

Started classA
Initiated Script
Looping
Into method run
Looping
Into method run
...

任何线索?

1 个答案:

答案 0 :(得分:1)

原因是当您执行logging.getLogger()时,类和脚本具有相同的logger对象。这是一个单身人士。如果你想要不同的记录器,那么你应该传递记录器名称,例如logging.getLogger('logger1') 通常,库会执行logging.getLogger(__name__),以便每个模块获得不同的记录器。参考http://docs.python.org/2/library/logging.html#logger-objects

我修改了您的代码,以便它按预期工作

import logging, logging.handlers
from logging.handlers import TimedRotatingFileHandler

class Logger(object):
    def __init__(self, log_filename, name):
        logging.basicConfig(format='%(asctime)s %(message)s')
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        loghandler = TimedRotatingFileHandler(
            log_filename, when="midnight", backupCount=50
        )
        loghandler.setFormatter(formatter)
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(loghandler)

    def getLogger(self):
        return self.logger


class ClassA(object):
    def __init__(self):
        log = Logger(log_filename='class_logger.log', name="Class")
        self.logger = log.getLogger()
        self.logger.info('Started ClassA')

    def run(self):
        self.logger.info('Into method run')


A = ClassA()
log = Logger(log_filename='script_logger.log', name="Script")
logger = log.getLogger()
logger.info('Initiated Script')

for x in range(5):
    logger.info('Looping')
    A.run()