selective logger disable/enable

Peter Otten __peter__ at web.de
Tue Jan 23 10:04:18 CET 2007


Gary Jefferson wrote:

> Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B',
> and each module has its own logger, created with:
> 
> module1logger = logging.getLogger('project.A')
> 
> and
> 
> module2logger = logging.getLogger('project.A.a')
> 
> and
> 
> module3logger = logging.getLogger('project.B')
> 
> 
> And I want to selectively enable/disable these, per module (for
> example, I only want logging from A and A.a, or just from B, etc).  It
> seems like logging.Filter is supposed to let me do this, but I can't
> see how to apply it globally.  Is there really no other way that to add
> a addFilter(filter) call to each of these loggers individually?
> 
> logging.basicConfig gets inherited by all loggers, but it doesn't seem
> capable of giving a Filter to all loggers.  Is there any way to do this?

An alternative approach might be to set the 'propagate' flag:

import logging

def warn_all(loggers, message):
    for lgr in loggers:
        lgr.warn(message)

logging.basicConfig()
root = logging.getLogger()
root.manager.emittedNoHandlerWarning = True
loggers = [logging.getLogger(name) for name in """
alpha
alpha.1
alpha.2
alpha.2.1
alpha.2.2
alpha.2.2.1
beta
beta.1
beta.2
""".split()]

warn_all(loggers, "all on")

print "---"
logging.getLogger("alpha").propagate = False
warn_all(loggers, "alpha off")
logging.getLogger("alpha").propagate = True

print "---"
logging.getLogger("alpha.2").propagate = False
warn_all(loggers, "alpha.2 off")

Peter



More information about the Python-list mailing list