Clearing out handlers in logging?

Peter Otten __peter__ at web.de
Sun Mar 16 05:18:15 EDT 2014


Gunther Dietrich wrote:

> Tim Chase <python.list at tim.thechases.com> wrote:
> 
>>The current (2.7; maybe 3.x?) logging module doesn't have any sort of
>>"clear out all the current handlers" method.
> 
> Indeed, THERE IS a removeHandler() method. In the documentation of
> python 2.6, it is mentioned in '16.6.5. Logger Objects', directly after
> the addHandler() method. If you found the addHandler() method there, you
> should have found removeHandler() too.
> 
> And a simple
> 
>>>> dir(log)
> ['__doc__', '__init__', '__module__', '_log', 'addFilter', 'addHandler',
> 'callHandlers', 'critical', 'debug', 'disabled', 'error', 'exception',
> 'fatal', 'filter', 'filters', 'findCaller', 'getEffectiveLevel',
> 'handle', 'handlers', 'info', 'isEnabledFor', 'level', 'log',
> 'makeRecord', 'manager', 'name', 'parent', 'propagate', 'removeFilter',
> 'removeHandler', 'root', 'setLevel', 'warn', 'warning']
> 
> also would have revealed it to you.
> 
> 
>>I can hack it by doing
>>
>>  log = logging.getLogger()  # get the root logger
>>  del log.handlers[:]        # reach inside and nuke 'em
>>  log.addHandler(...)        # install the one(s) I want
>>
>>but it feels a little dirty to reach into logging.root.handlers since
>>there are other methods for adding/removing handlers.  However, as
>>best I can tell, to remove a handler, you already need to have it
>>saved somewhere.
> 
> What about this:
> 
>>>> for handler in log.handlers:
> ...     log.removeHandler(handler)
> 
> I think, that's just one of the tasks that removeHandler() was written
> for.
> 
> 
>>Is there a better way to do this, or do I just suck it up and deal
>>with the (potentially thread-ignorant, as it doesn't lock) hack?
> 
> One of the best ways would be to read the documentation. And to do some
> exploration, e.g. by means of dir() and help(), could also be quite
> instructive. This experience cannot be replaced by
> documentation-research requests to the Usenet.

Hm, what do the docs say about this one?

>>> import logging
>>> logging.basicConfig()
>>> log = logging.getLogger("foo")
>>> for i in range(5):
...     log.addHandler(logging.FileHandler("tmp.log"))
... 
>>> assert len(log.handlers) == 5
>>> for handler in log.handlers:
...     log.removeHandler(handler)
... 
>>> log.handlers
[<logging.FileHandler object at 0x7f8217686e90>, <logging.FileHandler object 
at 0x7f8216f9eb90>]





More information about the Python-list mailing list