Reputation: 10320
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?
Upvotes: 4
Views: 2362
Reputation: 99530
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.
Upvotes: 5
Reputation: 77119
Probably not. Maybe yes. There could be. Who knows?
In other words, it depends on the Handler. They are not intended to be reused: some implementations may be okay with it, some may have internal state that can get messed up.
I would duplicate the object, instead of reusing it, as a rule of thumb.
Upvotes: 0