Issue 9606: logging filter is not applied to messages from descendant loggers (original) (raw)
I believe the following should print only one log message, not two:
import logging
class Filter(object):
def filter(self, record):
return record.name == 'foo'
logger = logging.getLogger()
formatter = logging.Formatter('%(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addFilter(Filter())
logger.addHandler(handler)
logging.getLogger('foo').warn('foo!')
logging.getLogger('bar').warn('bar!')
If the filter is added to the handler instead of the logger, everything works as expected.
If this is desired behaviour, please consider this a bug against the documentation. In that case I propose to extend the documentation of Logger.addFilter() as follows: "Note that the filter will act only on log messages that are generated by this logger, and not on messages that have been generated by descendant loggers."
The following paragraph has been added to the documentation for Filter objects in py3k and release27-maint branches (r84212):
"Note that filters attached to handlers are consulted whenever an event is emitted by the handler, whereas filters attached to loggers are consulted whenever an event is logged to the handler (using debug(), info(), etc.) This means that events which have been generated by descendant loggers will not be filtered by a logger's filter setting, unless the filter has also been applied to those descendant loggers."