Logging module gives duplicate log entries

Peter Otten __peter__ at web.de
Tue Aug 21 23:40:52 CEST 2007


Shiao wrote:

>> You need to remove the handler from the logging object
>>
>> # remove the handler once you are done
>> applog.removeHandler(hdl)

> I'm not sure how this could help.

If you have multiple handlers you'll get a logged message for every handler.

In your code logging.basicConfig() implicitly adds a handler and you add
another one calling addHandler(). Let's use a StreamHandler to see the
effect immediately:

>>> import logging
>>> logging.basicConfig()
>>> root = logging.getLogger()
>>> root.warn("once")
WARNING:root:once
>>> handler = logging.StreamHandler()
>>> root.addHandler(handler)
>>> root.warn("twice")
WARNING:root:twice
twice
>>> root.removeHandler(handler)
>>> root.warn("once again")
WARNING:root:once again

Of course it would be preferable not to add a second handler in the first
place, either by omitting the basicConfig() or the explicit addHandler()
call.

Peter



More information about the Python-list mailing list