How to do logging with python and avoid duplicate lines

TL;DR: If you use the default example your handlers are duplicated in each object instance

 

If you blindly follow the official python documentation at https://docs.python.org/3/howto/logging.html

 

you will probably end up with duplicate lines like me. The reason for this is, that each instance of your object will add a separate handler to the default logger. You will stumble upon code like this:

 

        logger = logging.getLogger()
        handler = logging.StreamHandler()
        formatter = logging.Formatter(
            '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        handler.setFormatter(formatter)
        logger.handlers
        logger.addHandler(handler)

        logger.setLevel(logging.DEBUG)

 

The easiest fix is to just add the handlers if they haven’t been added before. You can just copy & paste this in your __init__ function:

        logger = logging.getLogger()
        if not logger.handlers:
               handler = logging.StreamHandler()
               formatter = logging.Formatter(
                '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
               handler.setFormatter(formatter)
               logger.handlers
               logger.addHandler(handler)

        logger.setLevel(logging.DEBUG)