Python笔记:logging日志记录到文件及自动分割

日志作为项目开发和运行中必备组件,python提供了内置的logging模块来完成这个工作;借助TimedRotatingFileHandler可以按日期自动分割日志,自动保留日志文件数量等,下面是对日志的一个简单封装和测试。

import logging
import os
from logging import handlers


class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'critical': logging.CRITICAL
    }

    def __init__(
        self,
        *,
        filename,
        level='info',
        when='D',
        backup_count=3,
        fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
    ):
        f_dir, f_name = os.path.split(filename)
        os.makedirs(f_dir, exist_ok=True)
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)
        self.logger.setLevel(self.level_relations.get(level))
        sh = logging.StreamHandler()
        # 输出格式
        sh.setFormatter(format_str)
        # 输出到文件
        th = handlers.TimedRotatingFileHandler(
            filename=filename, when=when, backupCount=backup_count, encoding='utf-8'
        )
        th.setFormatter(format_str)
        # backupCount保留文件个数,
        # when间隔的时间单位
        # 可选:
        # S 秒
        # M 分
        # H 小时
        # D 天
        # 'W0'-'W6' 每星期几(星期一:W0)
        # midnight 每天凌晨
        self.logger.addHandler(sh)
        self.logger.addHandler(th)


# 测试
if __name__ == '__main__':
    logger = Logger('./logs/2020/app.log', 'debug', 'S', 5).logger
    logger.debug('debug')
    logger.info('info')
    logger.warning('警告')
    logger.error('报错')
    logger.critical('严重')

    # 单独记录error
    err_logger = Logger('./logs/2020/error.log', 'error', 'S', 3).logger
    err_logger.error('错误 error')

python使用logging记录日志到文件及自动分割

为了测试方便,我们将时间间隔设为秒(按秒自动命名分割文件),多运行几次后,会按照配置文件数量将多余的日志文件自动删除,保留如上图中的日志文件。

Python笔记:logging日志记录到文件及自动分割

原文链接:https://beltxman.com/3195.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

Scroll to top