Can we use the same handler for different loggers

logging, python

Solution

You're generally better off adding handlers to the highest-level logger that needs them. In your example, you could have achieved the same effect by only adding the handler to the root logger and not setting the `propagate` flag on the `sth` logger to `False`.

There should be no harm in adding the same handler to multiple loggers, but it may cause messages to be duplicated in the log if you don't disable propagation.

Many applications just add handlers to the root logger and let propagation take care of the rest, others add additional handlers to non-root loggers only for specific requirements.

Problem

Is it recommended to use the same handler for different loggers in Python. For example: ``` logger = logging.getLogger('sth') logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter('[%(levelname)1.1s %(asctime)s %(funcName)s:%(lineno)d] - %(message)s', '%y%m%d %H:%M:%S') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) logger.addHandler(handler) logger.propagate = False logging.getLogger().addHandler(handler) logging.getLogger().setLevel(logging.DEBUG) ``` Here I set up two loggers, one named 'sth', the other the root logger. And I assign the same handler to both loggers. It seems fine from my usage so far, but I wonder if there is any gotcha down the road?

Original source