Clearing out handlers in logging?
Gunther Dietrich
gd.usenet at spamfence.net
Sun Mar 16 04:39:40 EDT 2014
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.
Best regards,
Gunther
More information about the Python-list
mailing list