本文介紹了Python 根據日志級別打印不同顏色的日志的方法示例,分享給大家,具體如下:
# -*-coding:UTF-8-*-
import logging
import os
import time
class logger(object):
"""
終端打印不同顏色的日志,在pycharm中如果強行規定了日志的顏色, 這個方法不會起作用, 但是
對于終端,這個方法是可以打印不同顏色的日志的。
"""
#在這里定義StreamHandler,可以實現單例, 所有的logger()共用一個StreamHandler
ch = logging.StreamHandler()
def __init__(self):
self.logger = logging.getLogger()
if not self.logger.handlers:
#如果self.logger沒有handler, 就執行以下代碼添加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)
# 創建一個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")
實現過程:
終端的字符顏色是用轉義序列控制的,是文本模式下的系統顯示功能,和具體的語言無關。
轉義序列是以ESC開頭,即用\033來完成(ESC的ASCII碼用十進制表示是27,用八進制表示就是033)。
書寫格式:
開頭部分:\033[顯示方式;前景色;背景色m + 結尾部分:\033[0m
注意:開頭部分的三個參數:顯示方式,前景色,背景色是可選參數,可以只寫其中的某一個;另外由于
表示三個參數不同含義的數值都是唯一的沒有重復的,所以三個參數的書寫先后順序沒有固定要求,系統
都能識別;但是,建議按照默認的格式規范書寫。
對于結尾部分,其實也可以省略,但是為了書寫規范,建議\033[***開頭,\033[0m結尾。
數值表示的參數含義:
常見開頭格式:
- \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)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

