溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python 根據(jù)日志級(jí)別打印不同顏色的日志的方法示例

發(fā)布時(shí)間:2020-10-20 02:03:16 來(lái)源:腳本之家 閱讀:219 作者:YPFeime 欄目:開發(fā)技術(shù)

本文介紹了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í)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI