使用python logging模块时,如何在安装大小切割的时候指定自动生成的日志的文件名?

题目描述

使用python logging模块时,如何在安装大小切割的时候指定自动生成的日志的文件名?


logger = logging.getLogger('mylogger')
logger.setLevel(level=logger_level)
fmt = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
format_str = logging.Formatter(fmt)
fh = logging.FileHandler(fn, encoding='utf-8')
fh = logging.handlers.RotatingFileHandler(fn,maxBytes=10000,backupCount=10)
fh.setFormatter(fmt=format_str)
logger.addHandler(fh)

在使用RotatingFileHandler时,如何使它自动生成的类似‘log.1’的文件可以自定义文件名?

阅读 2.9k
评论
    1 个回答

    RotatingFileHandler继承自BaseRotatingHandler类,有一个方法如下

        def rotation_filename(self, default_name):
            """
            Modify the filename of a log file when rotating.
    
            This is provided so that a custom filename can be provided.
    
            The default implementation calls the 'namer' attribute of the
            handler, if it's callable, passing the default name to
            it. If the attribute isn't callable (the default is None), the name
            is returned unchanged.
    
            :param default_name: The default name for the log file.
            """
            if not callable(self.namer):
                result = default_name
            else:
                result = self.namer(default_name)
            return result

    这个方法是分割日志的时候进行命名转换的,
    namer是类的一个方法,默认是None

    如果没有的话,就会保存原名称,如果是一个可以调用的对象,就会将默认名作为参数传入,并将结果作为文件名.

    import logging
    from logging.handlers import RotatingFileHandler
    fn = "mylog.log"
    
    logger = logging.getLogger('mylogger')
    logger.setLevel(level=logging.DEBUG)
    fmt = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
    format_str = logging.Formatter(fmt)
    fh = RotatingFileHandler(fn, maxBytes=20, backupCount=5,encoding="utf-8")
    fh.namer = lambda x: "backup."+x.split(".")[-1] # 这里给namer赋值一个方法,注意后边的.1.2.3是一起传递过来的,要自己处理好
    
    
    fh.setFormatter(fmt=format_str)
    logger.addHandler(fh)
    
    for i in range(100):
        logger.debug("测试日志")
    

    clipboard.png
    修改前和修改后的文件名,mylog和backup

      撰写回答

      登录后参与交流、获取后续更新提醒