Python多个重复记录

时间:2019-05-16 08:53:24

标签: python logging

我有一个自定义记录器类,该类在一个模块中运行良好,但是如果在同一程序包的另一个模块中使用相同的文件处理程序,则将记录倍增1到n次。 我在5个线程中使用它,这就是为什么我每次记录消息时都试图关闭filehandler


class RootLogger():

    def __init__(self):
        self.logger = None

    # skeleton for creating custom logger
    # name - name of the logger, string or class/module name
    def set_config(self, name, logfile):
        self.logger = logging.getLogger(name)
        # format of the message
        formatter = logging.Formatter('%(asctime)s - [%(name)s] [%(levelname)s] %(message)s')
        # log file rotation, time
        handler = RotatingFileHandler(filename=logfile,
                                      maxBytes=8000000,
                                    backupCount=5,
                                    encoding='utf-8')
        #handler = StreamHandler()
        handler.setFormatter(formatter)
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(handler)
        self.logger.setLevel(logging.DEBUG)
        return self.logger

    # patch for excluding 'too many opened files' error
    def __del__(self):
        if self.logger:
            for hdlr in self.logger.handlers:
                #hdlr.flush()
                hdlr.close()
    # override commands
    def info(self, msg):
        self.logger.info(msg)
        self.__del__()
    def debug(self, msg):
        self.logger.debug(msg)
        self.__del__()
    def error(self, msg):
        self.logger.error(msg)
        self.__del__()
    def warning(self, msg):
        self.logger.warning(msg)
        self.__del__()
    def critical(self, msg):
        self.logger.warning(msg)
        self.__del__()

1 个答案:

答案 0 :(得分:1)

您想在创建更多处理程序之前检查记录器的处理程序是否存在。

self.logger = logging.getLogger(name)
if not self.logger.handlers:
    #Create the handlers