Python使用colorlog實(shí)現(xiàn)控制臺(tái)管理日志多種顏色顯示
colorlog 是一個(gè) Python 日志庫,它可以讓你在控制臺(tái)中以彩色的方式顯示日志消息,使得日志更易于閱讀和理解。該庫允許你為不同級(jí)別的日志消息設(shè)置不同的顏色,比如將錯(cuò)誤消息顯示為紅色,信息消息顯示為綠色等等。
效果圖
實(shí)現(xiàn)代碼
下面是我個(gè)人封裝的一個(gè)日志記錄庫:
import logging import colorlog import os from logging import handlers log_colors_config = { 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', } class LogHelper(object): level_relations = { 'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'crit':logging.CRITICAL }#日志級(jí)別關(guān)系映射 def __init__(self,filename,level='info',when='D',backCount=3): mexist=os.path.exists("log") if mexist == False: os.makedirs("log") self.logger = logging.getLogger(filename) ffmt='[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s' file_format_str = logging.Formatter(ffmt)#設(shè)置日志格式 fmt='%(log_color)s[%(asctime)s] - %(message)s' format_str = colorlog.ColoredFormatter(fmt,log_colors=log_colors_config) self.logger.setLevel(self.level_relations.get(level))#設(shè)置日志級(jí)別 sh = logging.StreamHandler()#往屏幕上輸出 sh.setFormatter(format_str) #設(shè)置屏幕上顯示的格式 th = handlers.TimedRotatingFileHandler(filename="log/"+filename,when=when,backupCount=backCount,encoding='utf-8')#往文件里寫入#指定間隔時(shí)間自動(dòng)生成文件的處理器 #實(shí)例化TimedRotatingFileHandler #interval是時(shí)間間隔,backupCount是備份文件的個(gè)數(shù),如果超過這個(gè)個(gè)數(shù),就會(huì)自動(dòng)刪除,when是間隔的時(shí)間單位,單位有以下幾種: # S 秒 # M 分 # H 小時(shí)、 # D 天、 # W 每星期(interval==0時(shí)代表星期一) # midnight 每天凌晨 th.setFormatter(file_format_str)#設(shè)置文件里寫入的格式 self.logger.addHandler(sh) #把對(duì)象加到logger里 self.logger.addHandler(th) if __name__ == '__main__': log = Logger('Log/all.log',level='debug') log.logger.debug('debug') log.logger.info('info') log.logger.warning('警告') log.logger.error('報(bào)錯(cuò)') log.logger.critical('嚴(yán)重') Logger('error.log', level='error').logger.error('error')
使用方法
from time import sleep import time from common import LogHelper logger = None #日志 dataSteps = None #步驟 mapList = None #映射關(guān)系 def main(): global logger logger = LogHelper.LogHelper("test.log") logger.logger.info('啟動(dòng)執(zhí)行') config = Config.readConfig(logger.logger) if config == None: logger.logger.error('讀取配置文件失敗,請(qǐng)檢查配置文件!') return ConfigCacheInfo.configDict = config
方法補(bǔ)充
除了上文的方法,小編還為大家整理了其他控制臺(tái)日志彩色顯示的方法,希望對(duì)大家有所幫助
使用logger 同時(shí)輸出到控制臺(tái)(顏色不同)和文件
import logging import colorlog log_colors_config = { 'DEBUG': 'white', # cyan white 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } logger = logging.getLogger('logger_name') # 輸出到控制臺(tái) console_handler = logging.StreamHandler() # 輸出到文件 file_handler = logging.FileHandler(filename='test.log', mode='a', encoding='utf8') # 日志級(jí)別,logger 和 handler以最高級(jí)別為準(zhǔn),不同handler之間可以不一樣,不相互影響 logger.setLevel(logging.DEBUG) console_handler.setLevel(logging.DEBUG) file_handler.setLevel(logging.INFO) # 日志輸出格式 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 -> %(funcName)s line:%(lineno)d [%(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) # 重復(fù)日志問題: # 1、防止多次addHandler; # 2、loggername 保證每次添加的時(shí)候不一樣; # 3、顯示完log之后調(diào)用removeHandler if not logger.handlers: logger.addHandler(console_handler) logger.addHandler(file_handler) console_handler.close() file_handler.close() if __name__ == '__main__': logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('critical')
結(jié)果如下
到此這篇關(guān)于Python使用colorlog實(shí)現(xiàn)控制臺(tái)管理日志多種顏色顯示的文章就介紹到這了,更多相關(guān)Python colorlog控制臺(tái)彩色顯示日志內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
tensorflow實(shí)現(xiàn)讀取模型中保存的值 tf.train.NewCheckpointReader
今天小編就為大家分享一篇tensorflow實(shí)現(xiàn)讀取模型中保存的值 tf.train.NewCheckpointReader,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python開發(fā)一個(gè)功能齊全的IM聊天工具(附實(shí)例代碼)
即時(shí)通訊(IM)工具現(xiàn)在已經(jīng)很常見了,從簡(jiǎn)單的文本聊天到文件傳輸、音視頻通話,IM 工具功能豐富,那么,本文使用Python開發(fā)一個(gè)基礎(chǔ)的IM聊天工具,包括:客戶端和服務(wù)端架構(gòu)、實(shí)時(shí)消息發(fā)送與接收、多用戶聊天支持、一個(gè)簡(jiǎn)單的圖形用戶界面(GUI)2024-12-12Python pyautogui模塊實(shí)現(xiàn)鼠標(biāo)鍵盤自動(dòng)化方法詳解
這篇文章主要介紹了Python pyautogui 模塊實(shí)現(xiàn)鼠標(biāo)鍵盤自動(dòng)化方法詳解,需要的朋友可以參考下2020-02-02Scrapy基于Python構(gòu)建強(qiáng)大網(wǎng)絡(luò)爬蟲框架實(shí)例探究
這篇文章主要為大家介紹了Scrapy基于Python構(gòu)建強(qiáng)大網(wǎng)絡(luò)爬蟲框架實(shí)例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01python庫pycryptodom加密技術(shù)探索(公鑰加密私鑰加密)
這篇文章主要為大家介紹了python庫pycryptodom加密技術(shù)探索(公鑰加密私鑰加密),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01python 數(shù)據(jù)分析實(shí)現(xiàn)長(zhǎng)寬格式的轉(zhuǎn)換
這篇文章主要介紹了python 數(shù)據(jù)分析實(shí)現(xiàn)長(zhǎng)寬格式的轉(zhuǎn)換,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05