python logging ensure a handler is added only once

Viewed 41759

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

logger = logging.getLogger()
hdlr = logging.FileHandler('logfile.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.DEBUG)

Unfortunately this code is being called multiple times, is there any way I can check to see if the handler already exists - I'd prefer to implement this without having to use a Singleton.

EDIT: Sorry, forgot to mention this is on python 2.5 - cheers, Richard

5 Answers

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

Related