python logging filters

Grimsqueaker grimsqueaker13 at gmail.com
Fri Nov 27 14:11:33 CET 2009


I have found some strange behaviour when using the Python 2.6 logging
module, maybe someone here can explain what's happening?

When I add a Filter to a Handler, everything works as expected (ie.
all messages sent from Loggers below the Filter's level are allowed
through), but when I add the Filter directly on to the Logger, only
that Logger is blocked, regardless of the contents of the Filter.

The code below will show the expected and desired output when run. To
see the inexplicable output, use the commented line in place of the
line above it.

code:

import logging


root_logger = logging.getLogger()
loggerA = logging.getLogger('A')

loggerA1 = logging.getLogger('A.1')

loggerA2 = logging.getLogger('A.2')

loggerA11 = logging.getLogger('A.1.1')

loggerA12 = logging.getLogger('A.1.2')

loggerB = logging.getLogger('B')

loggerB1 = logging.getLogger('B.1')

loggerB11 = logging.getLogger('B.1.1')


root_logger.addHandler(logging.StreamHandler())

f = logging.Filter(loggerB.name)

root_logger.handlers[0].addFilter(f)

#root_logger.addFilter(f)

for l in [root_logger, loggerA, loggerB, loggerA1, loggerA2, loggerB1,
loggerA11, loggerA12, loggerB11]:

    l.critical(l.name)

correct output:

B
B.1
B.1.1

weird output:

A
B
A.1
A.2
B.1
A.1.1
A.1.2
B.1.1


Thanks



More information about the Python-list mailing list