繁体   English   中英

具有类和循环日志处理的Python Logger模块

[英]Python Logger module with a class and rotating log handling

我正在将一组.py文件创建到一个“包”中,我希望所有人都导入一个标准化的“记录器”,该记录器允许所有模块都记录到一个文件中。

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并实例化该对象,它将找到具有相同名称的当前记录器,因此将日志记录到一个文件中...

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

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

谢谢

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

这是带有包装器的示例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM