Remove root handler from logger

Jean-Michel Pichavant jeanmichel at sequans.com
Mon May 14 05:34:50 EDT 2012


Florian Lindner wrote:
> Hello,
>
> I configure my logging on application startup like that:
>
> logging.basicConfig(level = logging.DEBUG, format=FORMAT, filename = logfile)
> ch  = logging.StreamHandler()
> ch.setFormatter(logging.Formatter(FORMAT))
> logging.getLogger().addHandler(ch)
>
> In one module of my application I want a logger that does not log to logfile 
> but to another file. How can I get a logger that is either plain (no handlers 
> attached) or remove a handler?
>
> The handlers that are derived from the root logger are not shown in handlers:
>
> (Pdb) logger1.handlers
> []
> (Pdb) logging.getLogger().handlers
> [<logging.FileHandler object at 0x7f3e8f6f0e90>, <logging.StreamHandler object 
> at 0x7f3e8f731450>]
>
> How can I remove the FileHandler and StreamHandler from logger1 without 
> affecting the root logger?
>
> logger1.removeHandler() does not work since there are no handlers on logger1.
>
> Thanks,
>
> Florian
>   
The usual pattern is that the root logger is handling all the events. 
Sub loggers are only raising log events.
Try to stick with this most of the time.

However in your case you need a sub logger to handle its logs in a 
different way. For that you have to add a handler to your sub logger and 
tells it to not sent log event to its parent.
If I remeber correctly, this is done by setting the 'propagate' 
attribute of you logger to 0.

That could look like (not tested):

import logging

root = logging.getLogger()
foo = logging.getLogger('foo')

root.addHandler(logging.StreamHandler())
foo.addHandler(logging.FileHandler('foo.log'))
foo.propagate = 0

Cheers,

JM



More information about the Python-list mailing list