Python Logger模块具有类和旋转日志处理功能

时间:2017-12-16 07:52:45

标签: python logging

我在一个'package'中创建了一组.py文件,我希望它们都能导入一个标准化的'logger',它允许所有模块记录到一个文件中。

class BaseLogger():
def __init__(self, module_name, specific_task_name):
    logging.basicConfig(
        filename="app." + specific_task_name + "." + module_name + ".log",
        format="%(levelname)-10s;%(asctime)s;%(module)s;%(funcName)s;%(message)s;%(thread)s;%(threadName)s",
        #level=logging.DEBUG
    )
    self.baselogger = logging.getLogger("app." + module_name + "." + specific_task_name )
    self.baselogger.setLevel('DEBUG')

所以我的想法是所有我的.py文件,导入BaseLogger并实例化该对象,它会找到一个同名的当前记录器,因此LOG归一个文件......

问题是我现在正在尝试创建一个旋转的日志结构而刚丢失...我已经添加到.basicConfig [无法迭代],我想我应该做一个self.baselogger.addHandler ..但这会使日志文件变空....

如何使用上面的“分类”实现创建一个旋转日志文件...或者我做错了?...

由于

1 个答案:

答案 0 :(得分:2)

您不需要类包装器,因为日志模块在设计上非常棒。您需要做的是注册/获取记录器并使用格式和文件处理程序对其进行配置。

以下是包装器的示例:

class BaseLogger(object):

    def __init__(self, module_name, specific_task_name):
        filename = "app." + specific_task_name + "." + module_name + ".log",
        format = ("%(levelname)-10s;%(asctime)s;%(module)s;%(funcName)s;"
                  "%(message)s;%(thread)s;%(threadName)s"),
        # you do not have to keep the reference
        # it is possible to get logger from anywhere using getLogger
        self.logger = logging.getLogger(specific_task_name)
        self.logger.setLevel(logging.INFO)

        # make sure to add RotatingFileHandler only once
        # you might need to update condition if you have more than 1 handler
        if not self.logger.handlers:
            fh = handlers.RotatingFileHandler(filename,
                                              mode='a',
                                              maxBytes=MAX_LOG_FILE_SIZE,
                                              backupCount=2,
                                              encoding=None,
                                              delay=0)
            fh.setLevel(logging.INFO)
            formatter = logging.Formatter(format)
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)

我会放弃一个课程并使用fabric函数:

def get_logger(name):
    # setup new logger here if it does not exist 
    # return instance if it is there
    pass
相关问题