日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python利用logging模塊實現根據日志級別打印不同顏色日志的代碼案例_python

作者:eliwang ? 更新時間: 2022-12-27 編程語言

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自帶的格式化字符串):

原文鏈接:https://www.cnblogs.com/eliwang/p/16708787.html

欄目分類
最近更新