網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
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í)/文件名稱/類(lèi)/方法名稱/代碼行數(shù)展示(這里可以自己手動(dòng)調(diào)整formatter參數(shù) 如果感覺(jué)展示太長(zhǎng)的話)
%(levelno)s: 打印日志級(jí)別的數(shù)值
%(levelname)s: 打印日志級(jí)別名稱
%(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: 打印線程名稱
%(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)
原文鏈接:https://blog.csdn.net/weixin_44861659/article/details/122951087
相關(guān)推薦
- 2023-12-08 Can‘t open the append-only file: Permission denied
- 2022-03-19 基于React?Hooks的小型狀態(tài)管理詳解_React
- 2022-08-19 WPF使用DrawingContext實(shí)現(xiàn)二維繪圖_C#教程
- 2022-08-22 如何使用Python?Matplotlib繪制條形圖_python
- 2022-10-15 Python?UnicodedecodeError編碼問(wèn)題解決方法匯總_python
- 2023-01-01 解決React報(bào)錯(cuò)No?duplicate?props?allowed_React
- 2021-11-06 C語(yǔ)言?如何用堆解決Topk問(wèn)題_C 語(yǔ)言
- 2022-08-30 ORACLE分區(qū)表轉(zhuǎn)換在線重定義DBMS_REDEFINITION_oracle
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支