網站首頁 編程語言 正文
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)
原文鏈接:https://blog.csdn.net/weixin_44861659/article/details/122951087
相關推薦
- 2023-08-01 TypeScript 中的字面量類型和聯合類型特性
- 2022-02-09 Qt5連接并操作PostgreSQL數據庫的實現示例_C 語言
- 2022-08-02 Python?的矩陣傳播機制Broadcasting和矩陣運算_python
- 2022-11-09 PostgreSQL?HOT與PHOT有哪些區別_PostgreSQL
- 2022-12-10 C++?vector與數組轉換寫入/讀出文件方式_C 語言
- 2022-11-23 一文教會你用正則表達式校驗日期時間格式_正則表達式
- 2022-10-16 python?os模塊使用方法介紹_python
- 2022-12-29 Kotlin?協程思維模型的引入使用建立_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支