其他分享
首页 > 其他分享> > 带薪摸鱼的第四天之logging日志封装

带薪摸鱼的第四天之logging日志封装

作者:互联网

1.logging封装代码:

import logging
import settings


class Logger:
    isirsta = None

    def __init__(self, rootname, file, fmt, encoding, debug):
        self.rootname = rootname
        self.file = file
        self.fmt = fmt
        self.encoding = encoding
        self.debug = debug

    def __new__(cls, *args, **kwargs):
        """
        实现简单的单例模式
        :param args:
        :param kwargs:
        :return:
        """
        if not cls.isirsta:
            cls.isirsta = super().__new__(cls)
            return cls.isirsta
        return cls.isirsta

    def logger_log(self):
        # 调试模式
        if self.debug:
            filelevel = logging.DEBUG
            consolelevel = logging.DEBUG
        else:
            filelevel = logging.WARNING
            consolelevel = logging.INFO

        # 设置等级
        loggers = logging.getLogger(self.rootname)
        loggers.setLevel(logging.DEBUG)

        # 创建日志处理器
        file = logging.FileHandler(filename=self.file, encoding=self.encoding)
        file.setLevel(filelevel)  # 设置写入文件的日志等级

        console = logging.StreamHandler()
        console.setLevel(consolelevel)  # 设置控制台输出日志的等级

        # 3. 创建格式化器
        fmts = logging.Formatter(fmt=self.fmt)

        # 4. 把格式化器添加到日志处理器上
        file.setFormatter(fmts)
        console.setFormatter(fmts)

        # 5. 把日志处理器添加到日志器
        loggers.addHandler(file)
        loggers.addHandler(console)

        return loggers


logger = Logger(**settings.LOGER_DATA).logger_log()

2.settings配置文件配置内容

# 日志
LOGER_DATA = {
    "rootname": "SupTech",
    "file": os.path.join(BASE_PATH, 'logs', 'log.log'),
    "fmt": "%(levelname)s %(asctime)s [%(filename)s-->line:%(lineno)d]:%(message)s",
    "encoding": "utf-8",
    "debug": False,
}

3.log.log日志存储文件

3.使用

4.解释

标签:file,logging,log,self,摸鱼,带薪,日志,cls
来源: https://blog.csdn.net/qq_38924521/article/details/122305640