Filters

Filters#

With filters, you can set specific rules for which messages should be passed to the output by handlers. Additionally, filters are a common place to customize the behavior of the logger.

import logging
from logging import LogRecord

Extra format fields#

With a custom filter, you can modify the structure of the LogRecord used for logging each record. By specifying a custom formatter, you can include any additional fields in the logger’s format as desired.


Consider the following example, where the logger’s messages include my_field.

test_logger = logging.getLogger("test_logger")

stream_handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s|%(name)s|%(my_field)s')
stream_handler.setFormatter(formatter)
test_logger.addHandler(stream_handler)

To make this work, you need to create a custom filter that adds the value of my_field to each LogRecord and add this logger to the

class CutomFilter(logging.Filter):
    my_field = ""
    def filter(self, record: LogRecord) -> bool:
        record.my_field = self.my_field
        return super().filter(record)

custom_filter = CutomFilter()
test_logger.addFilter(custom_filter)

Finally the way to use it. Here is calling some logging methods after specification custom_filter.my_filed = "value1".

custom_filter.my_field = "value1"
test_logger.critical("")
test_logger.warning("")
CRITICAL|test_logger|value1
WARNING|test_logger|value1

Each record will include a section with value1.

Now switch value1 to value2 and call record again.

custom_filter.my_field = "value2"
test_logger.critical("")
CRITICAL|test_logger|value2

It leads to the value2 in the last section.