0

我写了以下内容logger。如何将其连接到Django不同级别

import inspect
import logging
from datetime import datetime

from pythonjsonlogger import jsonlogger


class Logger:
    def __init__(self, name: str):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.INFO)
        console = logging.StreamHandler()
        log = logging.FileHandler(filename="logs.log")
        formatter = jsonlogger.JsonFormatter()
        log.setFormatter(formatter)
        log.setLevel(logging.INFO)
        console.setLevel(logging.ERROR)

        if self.logger.hasHandlers():
            self.logger.handlers.clear()

        self.logger.addHandler(log)
        self.logger.addHandler(console)

    def get_log_data(self):
        curframe = inspect.currentframe()
        self.calframe = inspect.getouterframes(curframe, 2)
        previous_frame = curframe.f_back
        self.lines = inspect.getframeinfo(previous_frame)[3]
        self.class_name = previous_frame.f_locals["self"].__class__.__name__
        time = datetime.now()
        self.log_time = time.strftime("%a, %d %b %Y %H:%M:%S%z")

    def log_error(self, message: str, traceback: str, parent_id: str):
        self.get_log_data()
        self.logger.error(
            message,
            extra={
                "datetime": self.log_time,
                "level": "ERROR",
                "class_name": self.class_name,
                "fnc_name": self.calframe[1][3],
                "parent_id": parent_id,
                "stack": traceback,
                "fnc_call": " -> ".join(self.lines),
            },
        )

    def log_info(self, message: str, parent_id: str = None):
        self.get_log_data()
        self.logger.info(
            message,
            extra={
                "datetime": self.log_time,
                "level": "INFO",
                "class_name": self.class_name,
                "fnc_name": self.calframe[1][3],
                "fnc_call": " -> ".join(self.lines),
                "parent_id": parent_id,
            },
        )
4

0 回答 0