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

Python Loguru日志封裝裝飾器實現(xiàn)過程

 更新時間:2024年03月01日 11:51:56   作者:搬磚路上的大馬猴  
這篇文章主要介紹了Python Loguru日志封裝裝飾器實現(xiàn)過程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧

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的一個內置函數(shù),用于檢查對象是否具有指定的屬性或方法。
        if not hasattr(cls, '_logger'):
            cls._setup_logger()
        return super().__new__(cls)
    @classmethod
    def _setup_logger(cls):
        logger.remove()
        # 設置日志文件路徑和格式
        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: 要輸出的內容
        :return: msg
        # 栗子
        MyLogs.log("info", "-----------分割線-----------")
        """
        getattr(cls.logger_h, level)(msg)
    @classmethod
    def log_decorator(cls, msg: str):
        """
         日志裝飾器,記錄函數(shù)的名稱、參數(shù)、返回值、運行時間和異常信息
         栗子:
            @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中<>被識別為顏色標簽而報錯
                args_str = re.sub(r"<([^<>]+)>", r"\<\1\>", str(args))  # 使用正則表達式替換<任意內容>為\<任意內容>
                kwargs_str = re.sub(r"<([^<>]+)>", r"\<\1\>", str(kwargs))  # 使用正則表達式替換<任意內容>為\<任意內容>
                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> 返回結果:{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)

輸出結果:

到此這篇關于Python Loguru日志封裝 - 裝飾器實現(xiàn)的文章就介紹到這了,更多相關Python Loguru日志封裝內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論