本文介紹了Python 根據(jù)日志級(jí)別打印不同顏色的日志的方法示例,分享給大家,具體如下:
# -*-coding:UTF-8-*-
import logging
import os
import time
class logger(object):
"""
終端打印不同顏色的日志,在pycharm中如果強(qiáng)行規(guī)定了日志的顏色, 這個(gè)方法不會(huì)起作用, 但是
對(duì)于終端,這個(gè)方法是可以打印不同顏色的日志的。
"""
#在這里定義StreamHandler,可以實(shí)現(xiàn)單例, 所有的logger()共用一個(gè)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)建一個(gè)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")
實(shí)現(xiàn)過(guò)程:
終端的字符顏色是用轉(zhuǎn)義序列控制的,是文本模式下的系統(tǒng)顯示功能,和具體的語(yǔ)言無(wú)關(guān)。
轉(zhuǎn)義序列是以ESC開頭,即用\033來(lái)完成(ESC的ASCII碼用十進(jìn)制表示是27,用八進(jìn)制表示就是033)。
書寫格式:
開頭部分:\033[顯示方式;前景色;背景色m + 結(jié)尾部分:\033[0m
注意:開頭部分的三個(gè)參數(shù):顯示方式,前景色,背景色是可選參數(shù),可以只寫其中的某一個(gè);另外由于
表示三個(gè)參數(shù)不同含義的數(shù)值都是唯一的沒有重復(fù)的,所以三個(gè)參數(shù)的書寫先后順序沒有固定要求,系統(tǒng)
都能識(shí)別;但是,建議按照默認(rèn)的格式規(guī)范書寫。
對(duì)于結(jié)尾部分,其實(shí)也可以省略,但是為了書寫規(guī)范,建議\033[***開頭,\033[0m結(jié)尾。
數(shù)值表示的參數(shù)含義:
常見開頭格式:
- \033[0m??????????? 默認(rèn)字體正常顯示,不高亮
- \033[32;0m?????? 紅色字體正常顯示
- \033[1;32;40m? 顯示方式: 高亮??? 字體前景色:綠色? 背景色:黑色
- \033[0;31;46m? 顯示方式: 正常??? 字體前景色:紅色? 背景色:青色
實(shí)例:
(1)print("\033[1;31;40m您輸入的帳號(hào)或密碼錯(cuò)誤!\033[0m")??
上方代碼的輸出格式為:字體高亮,紅色前景,黃色背景????? PS:前景色也就是字體的顏色
(2)print("\033[0;31m%s\033[0m" % "輸出紅色字符")
#上方代碼的輸出格式為:字體默認(rèn),紅色前景
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)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

