Python 根據(jù)日志級別打印不同顏色的日志的方法示例
本文介紹了Python 根據(jù)日志級別打印不同顏色的日志的方法示例,分享給大家,具體如下:
# -*-coding:UTF-8-*- import logging import os import time class logger(object): """ 終端打印不同顏色的日志,在pycharm中如果強行規(guī)定了日志的顏色, 這個方法不會起作用, 但是 對于終端,這個方法是可以打印不同顏色的日志的。 """ #在這里定義StreamHandler,可以實現(xiàn)單例, 所有的logger()共用一個StreamHandler ch = logging.StreamHandler() def __init__(self): self.logger = logging.getLogger() if not self.logger.handlers: #如果self.logger沒有handler, 就執(zhí)行以下代碼添加handler self.logger.setLevel(logging.DEBUG) from serviceProgram.utils.FileUtil import FileUtil rootPath = FileUtil.getProgrameRootPath() self.log_path = rootPath + '/logs' if not os.path.exists(self.log_path): os.makedirs(self.log_path) # 創(chuàng)建一個handler,用于寫入日志文件 fh = logging.FileHandler(self.log_path + '/runlog' + time.strftime("%Y%m%d", time.localtime()) + '.log', encoding='utf-8') fh.setLevel(logging.INFO) # 定義handler的輸出格式 formatter = logging.Formatter('[%(asctime)s] - [%(levelname)s] - %(message)s') fh.setFormatter(formatter) # 給logger添加handler self.logger.addHandler(fh) def debug(self, message): self.fontColor('\033[0;32m%s\033[0m') self.logger.debug(message) def info(self, message): self.fontColor('\033[0;34m%s\033[0m') self.logger.info(message) def warning(self, message): self.fontColor('\033[0;37m%s\033[0m') self.logger.warning(message) def error(self, message): self.fontColor('\033[0;31m%s\033[0m') self.logger.error(message) def critical(self, message): self.fontColor('\033[0;35m%s\033[0m') self.logger.critical(message) def fontColor(self, color): #不同的日志輸出不同的顏色 formatter = logging.Formatter(color % '[%(asctime)s] - [%(levelname)s] - %(message)s') self.ch.setFormatter(formatter) self.logger.addHandler(self.ch) if __name__ == "__main__": logger = logger() logger.info("12345") logger.debug("12345") logger.warning("12345") logger.error("12345")
實現(xiàn)過程:
終端的字符顏色是用轉義序列控制的,是文本模式下的系統(tǒng)顯示功能,和具體的語言無關。
轉義序列是以ESC開頭,即用\033來完成(ESC的ASCII碼用十進制表示是27,用八進制表示就是033)。
書寫格式:
開頭部分:\033[顯示方式;前景色;背景色m + 結尾部分:\033[0m
注意:開頭部分的三個參數(shù):顯示方式,前景色,背景色是可選參數(shù),可以只寫其中的某一個;另外由于
表示三個參數(shù)不同含義的數(shù)值都是唯一的沒有重復的,所以三個參數(shù)的書寫先后順序沒有固定要求,系統(tǒng)
都能識別;但是,建議按照默認的格式規(guī)范書寫。
對于結尾部分,其實也可以省略,但是為了書寫規(guī)范,建議\033[***開頭,\033[0m結尾。
數(shù)值表示的參數(shù)含義:
常見開頭格式:
- \033[0m 默認字體正常顯示,不高亮
- \033[32;0m 紅色字體正常顯示
- \033[1;32;40m 顯示方式: 高亮 字體前景色:綠色 背景色:黑色
- \033[0;31;46m 顯示方式: 正常 字體前景色:紅色 背景色:青色
實例:
(1)print("\033[1;31;40m您輸入的帳號或密碼錯誤!\033[0m")
上方代碼的輸出格式為:字體高亮,紅色前景,黃色背景 PS:前景色也就是字體的顏色
(2)print("\033[0;31m%s\033[0m" % "輸出紅色字符")
#上方代碼的輸出格式為:字體默認,紅色前景
LOG_INFO='INFO' LOG_ERROR='ERROR' LOG_WARNING='WARNING' LOG_NOTIFY='NOTIFY' LOG_DEBUG='DEBUG' LOG_USER='USER' def info_log(value): if log_level > 3: print("\033[0;37;40m%s\033[0m"%value) def error_log(value): if log_level != 0: print("\033[0;31;40m%s\033[0m"%value) def warning_log(value): if log_level > 1: print("\033[0;33;40m%s\033[0m"%value) def debug_log(value): if log_level > 5: print("\033[0;34;40m%s\033[0m"%value) def notify_log(value): if log_level > 2: print("\033[0;36;40m%s\033[0m"%value) def user_log(value): if log_level > 4: print("\033[0;32;40m%s\033[0m"%value) def ZLOG(log_type,value): switcher={ 'INFO':info_log, 'ERROR':error_log, 'WARNING':warning_log, 'DEBUG':debug_log, 'NOTIFY':notify_log, 'USER':user_log } return switcher[log_type](value) test="hello world" ZLOG(LOG_INFO,"output info log %s"%test)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Deepsort + Yolo 實現(xiàn)行人檢測和軌跡追蹤的方法
這篇文章主要介紹了Deepsort + Yolo 實現(xiàn)行人檢測和軌跡追蹤,本項目通過采用深度學習方法實現(xiàn)YOLO算法行人檢測和deepsort算法對人員定位的和軌跡跟蹤,需要的朋友可以參考下2021-09-09Python使用scrapy抓取網(wǎng)站sitemap信息的方法
這篇文章主要介紹了Python使用scrapy抓取網(wǎng)站sitemap信息的方法,涉及Python框架scrapy的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04淺析python實現(xiàn)動態(tài)規(guī)劃背包問題
這篇文章主要介紹了python實現(xiàn)動態(tài)規(guī)劃背包問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Python深度學習之Keras模型轉換成ONNX模型流程詳解
這篇文章主要介紹了Python深度學習之Keras模型轉換成ONNX模型流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-09-09