1

我会尽量恢复。我有我写的这门课:

日志类

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()

我的班级是什么样的:

A类模块

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')

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

所以script_logger.logclass_logger.log有以下内容:

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

有什么线索吗?

4

1 回答 1

1

原因是当您执行 logging.getLogger() 时,类和脚本具有相同的记录器对象。这是一个单例。如果您想要不同的记录器,那么您应该传递记录器名称,例如 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()
于 2013-08-08T04:34:51.483 回答