python logging模块封装

import logging
import os
import sys
import logging.handlers

formatter = logging.Formatter('%(asctime)s - %(filename)s [line:%(lineno)d] - %(levelname)s - %(message)s')


class LoggingClass:
    def __init__(self, name="mylogger", loglevel="WARNING", save=True, save_level=logging.WARNING, log_path=None,
                 update_freqency="M", save_interval=1):
        self.log_path = log_path  # 日志路径
        self.name = name  # logger得名称在控制台和log文件输出
        self.logging = logging
        self.loglevel = loglevel  # logger得等级控制台只会输出不低于改等级得log
        self.log_level = None # 标记位
        self.save_level = save_level  # 存储日志级别
        self.save = save  # 是否利用文件句柄处理
        self.format = logging.Formatter('%(asctime)s - %(filename)s [line:%(lineno)d] - %(levelname)s - %(message)s')
        self.date_format = "%y/%m%d %H:%M%S"
        self.save_interval = save_interval  # 日志保存间隔
        self.update_freqency = update_freqency  # 日志更新频率

    def init_rotaingfile_handler(self, logfile_name="init_rotaingfile_handler.log"):
        fh = self.logging.handlers.RotatingFileHandler(
            filename=logfile_name,
            mode='a',
            maxBytes=300,
            backupCount=7,
        )
        fh.setLevel(self.save_level)
        fh.setFormatter(self.format)
        return fh

    def init_timerotating_handler(self, logfile_name="myLOG.log"):
        fh = self.logging.handlers.TimedRotatingFileHandler(
            filename=logfile_name,
            when=self.update_freqency,
            interval=self.save_interval,
            backupCount=7
        )
        fh.setLevel(self.save_level)
        fh.setFormatter(self.format)
        return fh

    def init_streamHd(self):
        stream_handler = self.logging.StreamHandler(sys.stdout)
        stream_handler.setLevel(logging.INFO)
        stream_handler.setFormatter(self.format)
        return stream_handler

    def init_fileHd(self, log_file):
        file_handler = self.logging.FileHandler(log_file)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(self.format)
        return file_handler

    def init_logger(self, fh_type="1"):
        logger = self.logging.getLogger(__name__)
        if self.loglevel == "DEBUG":
            self.log_level = self.logging.DEBUG
        elif self.loglevel == "INFO":
            self.log_level = self.logging.INFO
        elif self.loglevel == "WARNING":
            self.log_level = self.logging.WARNING
        elif self.loglevel == "ERROR":
            self.log_level = self.logging.ERROR

        logger.setLevel(self.log_level)
        if self.save:
            log_file = os.path.join(self.log_path , self.name +".log")
            print(log_file,">>>>")
            if not os.path.exists(self.log_path):
                os.makedirs(self.log_path)
            if not os.path.exists(log_file):
                os.system("echo  >  %s" % log_file)

            if fh_type == "1":
                fh = self.init_fileHd(log_file)
                logger.addHandler(fh)
            elif fh_type == "2":
                fh = self.init_streamHd()
                logger.addHandler(fh)
            elif fh_type == "3":
                fh = self.init_rotaingfile_handler()
                logger.addHandler(fh)
            elif fh_type == "4":
                fh = self.init_timerotating_handler()
                logger.addHandler(fh)
        return logger
if __name__ == '__main__':
    logger_t = LoggingClass("the_log", "DEBUG", True, logging.WARNING, "logs").init_logger("1")
    logger_t.debug('debug message')
    logger_t.info('info message')
    logger_t.warning('warn message')
    logger_t.error('error message')
    logger_t.critical('critical message')

  

posted @ 2023-04-21 14:16  AndRew-A  阅读(116)  评论(0编辑  收藏  举报