首页 > 编程语言 >python利用logging模块实现根据日志级别打印不同颜色日志

python利用logging模块实现根据日志级别打印不同颜色日志

时间:2022-09-19 19:46:07浏览次数:57  
标签:logging log python self message 日志 logger

logger:日志器对象,可通过logging.getLogger()方法获取

handler:处理器对象,将日志信息输出到指定位置,可通过logger.addHandler()方法进行添加

formatter:格式器对象,输出格式化日志字符串

有时候同一个应用程序有不同的日志需求,比如将error级别的日志在控制台输出,critical级别的日志写入日志文件中,这就需要不同的handler来实现,然后均通过logger.addHandler()方法进行添加

代码:

# coding:utf-8

import logging
import colorlog


class Log:
    def __init__(self,name=None,log_level=logging.DEBUG):
        # 获取logger对象
        self.logger = logging.getLogger(name)

        # 避免重复打印日志
        self.logger.handlers = []

        # 指定最低日志级别:(critical > error > warning > info > debug)
        self.logger.setLevel(log_level)

        # 日志格化字符串
        console_fmt = '%(log_color)s%(asctime)s-%(threadName)s-%(filename)s-[line:%(lineno)d]-%(levelname)s: %(message)s'
        file_fmt = '%(asctime)s-%(threadName)s-%(filename)s-[line:%(lineno)d]-%(levelname)s: %(message)s'

        # 控制台输出不同级别日志颜色设置
        color_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'purple',
        }

        console_formatter = colorlog.ColoredFormatter(fmt=console_fmt,log_colors=color_config)
        file_formatter = logging.Formatter(fmt=file_fmt)

        # 输出到控制台
        console_handler = logging.StreamHandler()
        # 输出到文件
        file_handler = logging.FileHandler(filename=name,mode='a',encoding='utf-8')

        # 设置日志格式
        console_handler.setFormatter(console_formatter)
        file_handler.setFormatter(file_formatter)

        # 处理器设置日志级别,不同处理器可各自设置级别,默认使用logger日志级别
        # console_handler.setLevel(logging.WARNING)
        file_handler.setLevel(logging.ERROR) # 只有error和critical级别才会写入日志文件

        # logger添加处理器
        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)

    def debug(self,message):
        self.logger.debug(message)

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

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

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

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

if __name__ == '__main__':
    # 控制台只会显示warning及以上级别日志信息,而log.txt文件中则会记录error及以上级别日志信息
    log = Log(name='log.txt',log_level=logging.WARNING)
    log.debug('debug')
    log.info('info')
    log.warning('warning')
    log.error('error')
    log.critical('critical')

最终控制台按照指定颜色输出warning以上级别日志内容:

log.txt文件中写入了error及critical级别日志内容:

 

补充(python自带的格式化字符串):

 

标签:logging,log,python,self,message,日志,logger
From: https://www.cnblogs.com/eliwang/p/16708787.html

相关文章

  • Python获取UTC时间
    fromdatetimeimportdatetime,timedeltanow_time=datetime.now()utc_time=now_time-timedelta(hours=8)#减去8小时utc_time=utc_time.strftime("%Y-%m-%......
  • Python在字典中通过键名查找键值
    deffind(target,dict_data):""":paramtarget:需要查找的键名:paramdict_data:需要查找的列表:return:如果找到就返回对应键名的键值,否则提示没......
  • Python简单操作!!
    一文肝完Python文件操作知识!点击关注......
  • python读写文件模板记录
    目录读写模式读文件read(可选:size)一次性读全部内容readline()读取一行内容readlines()读取所有内容,返回列表从file中读取每行等同于readlines()的功能写......
  • Python多线程编程——threading模块
    本文参考:https://blog.csdn.net/youngwyj/article/details/124720041https://blog.csdn.net/youngwyj/article/details/124833126目录前言threading模块1.简介2.创建线......
  • python-程序控制-for
    1.for循环的一般形式fortmpVarinIterable:blocktmpVar是临时变量Iterable是可迭代对象第一行是循环条件,当对可迭代对象的迭代遍历结束时,for循......
  • Python: yield from
     importtimedefdubious():print(f"\033[32;40;7m{'dubiousstart'}\033[0m")whileTrue:send_value=yieldifsend_valueisNone:......
  • 力扣92(java&python)-反转链表Ⅱ(中等)
    题目:给你单链表的头指针head和两个整数 left和right,其中 left<=right。请你反转从位置left到位置right的链表节点,返回反转后的链表。示例1:输入:head=......
  • python主文件调用其他文件函数的方法
    关键:from文件名import函数名主文件(main.py)需要和包含子函数的文件(fun_cal_modulus8.py)放到同一路径下fun_cal_modulus8.pyfromnumpyimport*#8水平defc......
  • Python: 取消numpy科学计数法
    Numpy中默认是使用科学计数法来显示数据的,但是这种做法往往不利于我们观测数据,比如坐标数据等。那么如何取消numpy科学计数法呢,请往下看。np.set_printoptions()import......