Python Logging: Filters and Custom Filters

In addition to loggers, handlers, and formatters, Python’s logging module provides filters that allow you to control which log messages are processed. Filters can be used to filter messages based on their level, the logger’s name, or other criteria.

Built-in Filters

Python’s logging module includes several built-in filters:

  • Filter: The base class for custom filters.
  • LevelFilter: Filters messages based on their level.
  • BasicFilter: Filters messages based on the logger’s name.

Example:

Python

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Create a filter to only log messages at the DEBUG level
filter = logging.Filter(name="app.module1")
logger.addFilter(filter)

logger.debug("This message will be logged")
logger.info("This message will not be logged")

Creating Custom Filters

You can create custom filters by subclassing the Filter class and implementing the filter(record) method. This method should return True if the record should be logged and False otherwise.

Example:

Python

import logging

class CustomFilter(logging.Filter):
    def filter(self, record):
        return record.levelno >= logging.WARNING

logger = logging.getLogger(__name__)
logger.addFilter(CustomFilter())

logger.debug("This message will not be logged")
logger.warning("This message will be logged")

Using Filters with Handlers

You can add filters to handlers to control which messages are processed by the handler.

Example:

Python

handler = logging.StreamHandler()
handler.addFilter(CustomFilter())
logger.addHandler(handler)
Handling HTTPExceptions with a Custom Exception Handler
Implementing Logging in FastAPI Endpoints

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?