Skip to content Skip to sidebar Skip to footer

Python: Logging: Can We Added Multiple Filters To The Logger And Which One Is Considered

I am trying to understand how multiple Filters (one defined in config and other in the code) in Python logging work. I am working on a Django project and below is my logger config

Solution 1:

Create only one filter and use it's instance to control if logs should be accepted or not.

from logging import getLogger

classLoggerGate(object):

    def__init__(self):
        self.started = Falsedefstart(self):
        self.started = Truedefstop(self):
        self.started = Falsedeffilter(self, record):
        """
        Determine if the specified record is to be logged.

        Returns True is this LoggerGate is started, False otherwise.
        """return self.started


logger_database = getLogger("log_testing")
logger_gate = LoggerGate()
logger_database.addFilter(logger_gate)

logger_database.critical('this is not logged')
logger_gate.start()
logger_database.critical('this is logged')
logger_gate.stop()
logger_database.critical('this is not logged')

Solution 2:

Gabriel C gives a great solution. And to explain more, filter works in sequence, which means the record is passed to each filter one by one. And will stop at the one returns a zero. So as your StartFilter returns 0, it will directly drop all records.

Post a Comment for "Python: Logging: Can We Added Multiple Filters To The Logger And Which One Is Considered"