python logging ensure a handler is added only once

前端 未结 5 694
时光取名叫无心
时光取名叫无心 2020-12-25 09:59

I have a piece of code that is initializing a logger as below.

logger = logging.getLogger()
hdlr = logging.FileHandler(\'logfile.log\')
formatter = logging.         


        
5条回答
  •  醉梦人生
    2020-12-25 10:33

    You can also just check to see whether the handler list is empty. Here's the solution I wound up with:

    def setup_logging(self, logfile):
        self._logger = logging.getLogger('TestSuite')
        self._logger.setLevel(logging.INFO)
        host = socket.gethostname().split('.')[0]
        if self._logger.handlers == []:
            fh = logging.handlers.RotatingFileHandler(logfile,
                                                      maxBytes=10*1024*1024,
                                                      backupCount=5)
            strfmt = "%" + "(asctime)s [%s] " % host + "%" + "(message)s"
            fmt = logging.Formatter(strfmt, datefmt="%Y.%m%d %H:%M:%S")
            fh.setFormatter(fmt)
    
            self._logger.addHandler(fh)
        self._logger.info('-' * (55 - len(host)))
    

    I was seeing the handler added multiple times, so each log message was getting written to the log file more than once, and this fixed it.

提交回复
热议问题