python logging ensure a handler is added only once

前端 未结 5 812
时光取名叫无心
时光取名叫无心 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:23

    If you are familiar with AWS Lambda, then you might already know that in some contexts, the handlers come pre-configured [1]. Assuming logger.handlers is not empty, is not enough. I recommend setting an attribute on the logger instance, like so:

    def init_logger(logger):
        if hasattr(logger, 'initialized'):
            return logger  # No need for addHandler
        else:
            setattr(logger, 'initialized', True)
    
        # Initialize the logger
        # ...
    

    [1] Using python Logging with AWS Lambda

提交回复
热议问题