Python Loguru日志封裝裝飾器實現(xiàn)過程
更新時間:2024年03月01日 11:51:56 作者:搬磚路上的大馬猴
這篇文章主要介紹了Python Loguru日志封裝裝飾器實現(xiàn)過程,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
Python Loguru日志封裝
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # @Time : 2023/6/25 15:49 # @Author : jingang.hou082613@gmail.com # @Site : # @File : operateLogs.py # @Software: PyCharm """ 日志處理 """ import inspect import os import re import sys from functools import wraps from time import strftime from time import perf_counter from base.singletonModel import Singleton from loguru import logger from utils.operateFile._ini import IniFile class MyLogs(metaclass=Singleton): LOG_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "../logs") # 存放日志 INI_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "../config/log_config.ini") # ini配置文件 ini_data = IniFile(INI_DIR).get_itemsAll() # 獲取ini配置中的數(shù)據(jù) logger_h = logger.opt(colors=True) def __new__(cls, *args, **kwargs): # hasattr是Python的一個內(nèi)置函數(shù),用于檢查對象是否具有指定的屬性或方法。 if not hasattr(cls, '_logger'): cls._setup_logger() return super().__new__(cls) @classmethod def _setup_logger(cls): logger.remove() # 設(shè)置日志文件路徑和格式 filename = strftime("%Y%m%d-%H%M%S") log_file_path = os.path.join(cls.LOG_DIR, f'{filename}.log') log_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | " \ "<level>{level}</level> " \ "| <level>{message}</level>" level_: str = MyLogs.ini_data["level"] rotation_: str = MyLogs.ini_data["rotation"] # 添加日志處理器:寫入文件 cls.logger_h.add(log_file_path, enqueue=True, backtrace=True, diagnose=True, encoding="utf8", rotation=rotation_ ) # 添加日志處理器:控制臺輸出 cls.logger_h.add( sys.stderr, format=log_format, enqueue=True, colorize=True, backtrace=True, diagnose=True, level=level_, # filter=cls._debug_filter # 使用自定義過濾器函數(shù) ) # @staticmethod # def _debug_filter(record): # """自定義過濾器函數(shù),僅輸出 DEBUG 級別的日志""" # if record["level"].name == MyLogs.ini_data["filter_level"]: # return True # return False @classmethod def log(cls, level: str, msg: str): """ ··· :param level: 日志等級:info,debug,trace,error,warning,critical,exception :param msg: 要輸出的內(nèi)容 :return: msg # 栗子 MyLogs.log("info", "-----------分割線-----------") """ getattr(cls.logger_h, level)(msg) @classmethod def log_decorator(cls, msg: str): """ 日志裝飾器,記錄函數(shù)的名稱、參數(shù)、返回值、運(yùn)行時間和異常信息 栗子: @log.log_decorator("這里填寫def功能") def test_zero_division_error(a, b): return a / b """ def decorator(func): func_line = inspect.currentframe().f_back.f_lineno @wraps(func) def wrapper(*args, **kwargs): # 處理報錯:args中<>被識別為顏色標(biāo)簽而報錯 args_str = re.sub(r"<([^<>]+)>", r"\<\1\>", str(args)) # 使用正則表達(dá)式替換<任意內(nèi)容>為\<任意內(nèi)容> kwargs_str = re.sub(r"<([^<>]+)>", r"\<\1\>", str(kwargs)) # 使用正則表達(dá)式替換<任意內(nèi)容>為\<任意內(nèi)容> cls.log("info", "\n") cls.log("info", "<green>-----------分割線-----------</>") cls.log("info", f"<white>{msg} ↓↓↓</>") cls.log("debug", f'<red>{func.__qualname__}:{func.__name__}:{func_line} |</> <white> args: {args_str}, kwargs:{kwargs_str}</>') start = perf_counter() try: result = func(*args, **kwargs) result_str = re.sub(r"<([^<>]+)>", r"\<\1\>", str(result)) end = perf_counter() duration = end - start cls.log("debug", f"<red>{func.__qualname__}:{func.__name__}:{func_line} |</> <white> 返回結(jié)果:{result_str}, 耗時:{duration:4f}s</>") return result except Exception as e: cls.log("exception", f"<red>{func.__qualname__}:{func.__name__}:{func_line} |</>: {msg}:報錯 :{e}") sys.exit(1) finally: cls.logger_h.complete() cls.log("info", "<green>-----------分割線-----------</>") return wrapper return decorator MyLogs() if __name__ == '__main__': MyLogs.log("debug", "Executing step 3 of the algorithm") MyLogs.log("info", "Server started on port") MyLogs.log("warning", "Invalid input provided, using default values") MyLogs.log("error", "Invalid user input detected, unable to proceed") MyLogs.log("critical", "Database connection lost, terminating the application") MyLogs.log("exception", "exception connection lost, terminating the application") @MyLogs.log_decorator("1111111111111111111") def A(a, b): a / b A(1, 0)
輸出結(jié)果:
到此這篇關(guān)于Python Loguru日志封裝 - 裝飾器實現(xiàn)的文章就介紹到這了,更多相關(guān)Python Loguru日志封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux 下python多線程遞歸復(fù)制文件夾及文件夾中的文件
這篇文章主要介紹了linux 下python多線程遞歸復(fù)制文件夾及文件夾中的文件,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01python3 pandas 讀取MySQL數(shù)據(jù)和插入的實例
下面小編就為大家分享一篇python3 pandas 讀取MySQL數(shù)據(jù)和插入的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04python中K-means算法基礎(chǔ)知識點(diǎn)
在本篇文章里小編給大家整理的是一篇關(guān)于python中K-means算法基礎(chǔ)知識點(diǎn)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。2021-01-01python自帶tkinter庫實現(xiàn)棋盤覆蓋圖形界面
這篇文章主要為大家詳細(xì)介紹了python自帶tkinter庫實現(xiàn)棋盤覆蓋圖形界面,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07Pycharm激活方法及詳細(xì)教程(詳細(xì)且實用)
這篇文章主要介紹了Pycharm激活方法及詳細(xì)教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-05-05卸載所有通過pip安裝的Python包的方法總結(jié)(Windows系統(tǒng))
這篇文章主要介紹了卸載所有通過pip安裝的Python包的方法總結(jié)(Windows系統(tǒng)),文中通過代碼示例和圖文講解的非常詳細(xì),并具有一定的參考價值,需要的朋友可以參考下2024-08-08