欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python自定義封裝帶顏色的logging模塊

 更新時(shí)間:2022年02月18日 15:17:37   作者:不能知道我是誰(shuí)  
大家好,本篇文章主要講的是python自定義封裝帶顏色的logging模塊,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下

python 自定義封裝帶顏色的logging模塊

自己在搭建python接口自動(dòng)化框架 分享一些內(nèi)容過(guò)程中想自己封裝一個(gè)logger方法 根據(jù)logging進(jìn)行二次封裝 代碼如下

import logging
import os
import time
import colorlog
from logging.handlers import RotatingFileHandler
# 創(chuàng)建文件目錄
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)  # 如果不存在這個(gè)logs文件夾,就自動(dòng)創(chuàng)建一個(gè)
# 修改log保存位置
timestamp = time.strftime("%Y-%m-%d", time.localtime())
logfile_name = '%s.log' % timestamp
logfile_path = os.path.join(log_path, logfile_name)
# 定義不同日志等級(jí)顏色
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
       # 針對(duì)所需要的日志信息 手動(dòng)調(diào)整顏色
       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='%'
       )  # 日志輸出格式
       # 創(chuàng)建一個(gè)FileHandler,用于寫(xiě)到本地
       rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfile_path,
                                                                  maxBytes=1024 * 1024 * 50,
                                                                  backupCount=5)
       rotatingFileHandler.setFormatter(formatter)
       rotatingFileHandler.setLevel(logging.DEBUG)
       self.addHandler(rotatingFileHandler)
       # 創(chuàng)建一個(gè)StreamHandler,用于輸出到控制臺(tái)
       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)

使用時(shí)我們只需要引入封裝好的類(lèi)就行 直觀美麗大方~

# 引入封裝好的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)
      # 使用時(shí)直接調(diào)用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)

效果:按照 日期/時(shí)間/日志等級(jí)/文件名稱(chēng)/類(lèi)/方法名稱(chēng)/代碼行數(shù)展示(這里可以自己手動(dòng)調(diào)整formatter參數(shù) 如果感覺(jué)展示太長(zhǎng)的話)
%(levelno)s: 打印日志級(jí)別的數(shù)值
%(levelname)s: 打印日志級(jí)別名稱(chēng)
%(pathname)s: 打印當(dāng)前執(zhí)行程序的路徑,其實(shí)就是sys.argv[0]
%(filename)s: 打印當(dāng)前執(zhí)行程序名
%(funcName)s: 打印日志的當(dāng)前函數(shù)
%(lineno)d: 打印日志的當(dāng)前行號(hào)
%(asctime)s: 打印日志的時(shí)間
%(thread)d: 打印線程ID
%(threadName)s: 打印線程名稱(chēng)
%(process)d: 打印進(jìn)程ID
%(message)s: 打印日志信息

在這里插入圖片描述

避坑:不要用這種方式去調(diào)用日志等級(jí)方法 會(huì)出現(xiàn)日志打印定位路徑錯(cuò)誤 只能定位在log封裝類(lèi)當(dāng)前方法下

  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)
      

到此這篇關(guān)于python自定義封裝帶顏色的logging模塊的文章就介紹到這了,更多相關(guān)python logging模塊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解在Anaconda環(huán)境下Python安裝pydot與graphviz的方法

    詳解在Anaconda環(huán)境下Python安裝pydot與graphviz的方法

    這篇文章主要為大家詳細(xì)介紹了在Anaconda環(huán)境中,安裝Python語(yǔ)言pydot與graphviz兩個(gè)模塊的方法,文中的安裝方法講解詳細(xì),感興趣?的可以了解一下
    2023-02-02
  • python實(shí)現(xiàn)雨滴下落到地面效果

    python實(shí)現(xiàn)雨滴下落到地面效果

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)雨滴下落到地面效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Python 數(shù)據(jù)結(jié)構(gòu)之堆棧實(shí)例代碼

    Python 數(shù)據(jù)結(jié)構(gòu)之堆棧實(shí)例代碼

    這篇文章主要介紹了Python 數(shù)據(jù)結(jié)構(gòu)之堆棧實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-01-01
  • 關(guān)于sklearn中模塊包導(dǎo)入報(bào)錯(cuò)的通用解決方法

    關(guān)于sklearn中模塊包導(dǎo)入報(bào)錯(cuò)的通用解決方法

    這篇文章主要介紹了關(guān)于sklearn中模塊包導(dǎo)入報(bào)錯(cuò)的通用解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • python RabbitMQ 使用詳細(xì)介紹(小結(jié))

    python RabbitMQ 使用詳細(xì)介紹(小結(jié))

    這篇文章主要介紹了python RabbitMQ 使用詳細(xì)介紹(小結(jié)),詳細(xì)的介紹了RabbitMQ的概念以及使用,對(duì)學(xué)習(xí)RabbitMQ有一定的幫助,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2018-11-11
  • python去掉 unicode 字符串前面的u方法

    python去掉 unicode 字符串前面的u方法

    今天小編就為大家分享一篇python去掉 unicode 字符串前面的u方法。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • Python代碼實(shí)現(xiàn)雙鏈表

    Python代碼實(shí)現(xiàn)雙鏈表

    這篇文章主要為大家詳細(xì)介紹了Python代碼實(shí)現(xiàn)雙鏈表,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • Python實(shí)現(xiàn)的線性回歸算法示例【附csv文件下載】

    Python實(shí)現(xiàn)的線性回歸算法示例【附csv文件下載】

    這篇文章主要介紹了Python實(shí)現(xiàn)的線性回歸算法,涉及Python使用最小二乘法、梯度下降算法實(shí)現(xiàn)線性回歸相關(guān)算法操作與使用技巧,需要的朋友可以參考下
    2018-12-12
  • 在python中pandas的series合并方法

    在python中pandas的series合并方法

    今天小編就為大家分享一篇在python中pandas的series合并方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-11-11
  • Python定時(shí)器實(shí)例代碼

    Python定時(shí)器實(shí)例代碼

    這篇文章主要介紹了Python定時(shí)器實(shí)例代碼,向大家分享了兩部分代碼示例,一個(gè)是通過(guò)線程實(shí)現(xiàn)定時(shí)器timer,另一個(gè)是Python實(shí)現(xiàn)的精度可調(diào)的定時(shí)器實(shí)例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11

最新評(píng)論