python 自定义封装带颜色的logging模块

自己在搭建python接口自动化框架 分享一些内容过程中想自己封装一个logger方法 根据logging进行二次封装 代码如下

import logging
import os
import time
import colorlog
from logging.handlers import rotatingfilehandler
# 创建文件目录
cur_path = os.path.dirname(os.path.realpath(__file__))  # log_path是存放日志的路径
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
if not os.path.exists(log_path): os.mkdir(log_path)  # 如果不存在这个logs文件夹,就自动创建一个
# 修改log保存位置
timestamp = time.strftime("%y-%m-%d", time.localtime())
logfile_name = '%s.log' % timestamp
logfile_path = os.path.join(log_path, logfile_name)
# 定义不同日志等级颜色
log_colors_config = {
   'debug': 'bold_cyan',
   'info': 'bold_green',
   'warning': 'bold_yellow',
   'error': 'bold_red',
   'critical': 'red',
}


class logger(logging.logger):
   def __init__(self, name, level='debug', file=none, encoding='utf-8'):
       super().__init__(name)
       self.encoding = encoding
       self.file = file
       self.level = level
       # 针对所需要的日志信息 手动调整颜色
       formatter = colorlog.coloredformatter(
           '%(log_color)s%(levelname)1.1s %(asctime)s %(reset)s| %(message_log_color)s%(levelname)-8s %(reset)s| %('
           'log_color)s[%(filename)s%(reset)s:%(log_color)s%(module)s%(reset)s:%(log_color)s%(funcname)s%('
           'reset)s:%(log_color)s%(''lineno)d] %(reset)s- %(white)s%(message)s',
           reset=true,
           log_colors=log_colors_config,
           secondary_log_colors={
               'message': {
                   'debug': 'blue',
                   'info': 'blue',
                   'warning': 'blue',
                   'error': 'red',
                   'critical': 'bold_red'
               }
           },
           style='%'
       )  # 日志输出格式
       # 创建一个filehandler,用于写到本地
       rotatingfilehandler = logging.handlers.rotatingfilehandler(filename=logfile_path,
                                                                  maxbytes=1024 * 1024 * 50,
                                                                  backupcount=5)
       rotatingfilehandler.setformatter(formatter)
       rotatingfilehandler.setlevel(logging.debug)
       self.addhandler(rotatingfilehandler)
       # 创建一个streamhandler,用于输出到控制台
       console = colorlog.streamhandler()
       console.setlevel(logging.debug)
       console.setformatter(formatter)
       self.addhandler(console)
       self.setlevel(logging.debug)


logger = logger(name=logfile_path, file=logfile_path)

使用时我们只需要引入封装好的类就行 直观美丽大方~

# 引入封装好的logger模块
from common.logger_handler import logger

def physical_strength(self, abnormal):
  """兑换体力异常通用方法"""
  if self.attrs.__contains__('costtype'):
      attrs_type = {
          "costtype": abnormal,
          "count": self.attrs["count"]
      }
      response_type = r().response(self.send_uid, self.code, self.event, attrs_type)
      # 使用时直接调用logger.info()就行
      logger.info(f"physical_strength_{abnormal},response_type:{response_type}")
      assert response_type["code"] != 0
      time.sleep(2)
      attrs_count = {
          "costtype": self.attrs["costtype"],
          "count": abnormal
      }
      response_count = r().response(self.send_uid, self.code, self.event, attrs_count)
      logger.info(f"physical_strength_{abnormal},response_count:{response_count}")
      assert response_count["code"] != 0
      time.sleep(2)
      attrs_all = {
          "costtype": abnormal,
          "count": abnormal
      }
      response_all = r().response(self.send_uid, self.code, self.event, attrs_all)
      logger.info(f"physical_strength_{abnormal},response_all:{response_all}")
      assert response_all["code"] != 0
      time.sleep(2)
  else:
      attrs_count = {
          "count": abnormal
      }
      response_count = r().response(self.send_uid, self.code, self.event, attrs_count)
      logger.info(f"physical_strength_{abnormal},response_count:{response_count}")
      assert response_count["code"] != 0
      time.sleep(2)

效果:按照 日期/时间/日志等级/文件名称/类/方法名称/代码行数展示(这里可以自己手动调整formatter参数 如果感觉展示太长的话)
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcname)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程id
%(threadname)s: 打印线程名称
%(process)d: 打印进程id
%(message)s: 打印日志信息

避坑:不要用这种方式去调用日志等级方法 会出现日志打印定位路径错误 只能定位在log封装类当前方法下

  def debug(self, message):
      self.__console('debug', message)

  def info(self, message):
      self.__console('info', message)

  def warning(self, message):
      self.__console('warning', message)

  def error(self, message):
      self.__console('error', message)
      

到此这篇关于python自定义封装带颜色的logging模块的文章就介绍到这了,更多相关python logging模块内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!