python 基于logging的封装日志类: 实现彩色日志、动态保留近一周log日志、兼容linux、win(直接使用即可)

背景:项目大了,日志混乱。需要进行规范。方便调试和查看。

功能:封装成工具类方便后续使用。直接保存为单独的py文件即可直接运行。

语音:python3.7+。推荐3.9

包含功能:彩色日志,只保留7天数据。日志分级别打印,兼容linux和win系统。

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
create:
author:
fuction:
"""
import logging
import os

import colorlog
import platform
import re
from logging.handlers import TimedRotatingFileHandler


class Logger(object):
    def __init__(self, log_name="test"):
        log_colors_config = {
            'DEBUG': 'white',  # cyan white
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red'
        }

        self.logger = logging.getLogger(name=log_name)
        # 输出到控制台
        console_handler = logging.StreamHandler()
        # interval 滚动周期,
        # when="MIDNIGHT", interval=1 表示每天0点为更新点,每天生成一个文件
        # backupCount  表示日志保存个数
        current_path = os.path.dirname(__file__)
        if platform.system().lower() == "windows":
            parent_path = os.path.dirname(current_path) + "\log\debug.log"
        else:
            parent_path = os.path.dirname(current_path) + "/log/debug.log"
        #print(f"current_path={current_path}")
        file_handler = TimedRotatingFileHandler(
            filename=parent_path, when="MIDNIGHT", interval=1, backupCount=3
        )
        # 输出到文件
        # filename="mylog" suffix设置,会生成文件名为mylog.2020-02-25.log
        file_handler.suffix = "%Y-%m-%d.log"
        # 需要注意的是suffix和extMatch一定要匹配的上,如果不匹配,过期日志不会被删除。
        file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
        # file_handler = logging.FileHandler(filename='debug.log', mode='a', encoding='utf8')

        # 日志级别,logger 和 handler以最高级别为准,不同handler之间可以不一样,不相互影响
        if platform.system().lower() == "windows":
            self.logger.setLevel(logging.DEBUG)
            console_handler.setLevel(logging.DEBUG)
            file_handler.setLevel(logging.ERROR)
        else:
            self.logger.setLevel(logging.DEBUG)
            console_handler.setLevel(logging.DEBUG)
            file_handler.setLevel(logging.ERROR)

        # 日志输出格式
        pass
        # 日志输出格式
        file_formatter = logging.Formatter(
            fmt='[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s',
            datefmt='%Y-%m-%d  %H:%M:%S'
        )
        console_formatter = colorlog.ColoredFormatter(
            fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> line:%(lineno)d %(funcName)s [%(levelname)s] : %(message)s',
            datefmt='%Y-%m-%d  %H:%M:%S',
            log_colors=log_colors_config
        )
        console_handler.setFormatter(console_formatter)
        file_handler.setFormatter(file_formatter)

        # 重复日志问题:
        # 1、防止多次addHandler;
        # 2、loggername 保证每次添加的时候不一样;
        # 3、显示完log之后调用removeHandler
        if not self.logger.handlers:
            self.logger.addHandler(console_handler)
            self.logger.addHandler(file_handler)

        console_handler.close()
        file_handler.close()

    def debug(self, msg):
        """
        定义输出的颜色debug--white,info--green,warning/error/critical--red
        :param msg: 输出的log文字
        :return:
        """
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)


log = Logger()

if __name__ == '__main__':
    log = Logger("test")
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('warning')
    log.logger.error('error')
    log.critical('critical')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值