首页 > 编程 > Python > 正文

Python 根据日志级别打印不同颜色的日志的方法示例

2019-11-25 12:03:58
字体:
来源:转载
供稿:网友

本文介绍了Python 根据日志级别打印不同颜色的日志的方法示例,分享给大家,具体如下:

# -*-coding:UTF-8-*-import loggingimport osimport 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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表