'Can't add custom filter to logger

I have the following filter to add colors:

class CustomFilter(logging.Filter):

    COLOR = {
        "DEBUG": "GREEN",
        "INFO": "GREEN",
        "WARNING": "YELLOW",
        "ERROR": "RED",
        "CRITICAL": "RED",
    }

    def filter(self, record):
        record.color = CustomFilter.COLOR[record.levelname]
        return True

applied to logger with format "%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s(%(lineno)d) - %(message)s"

So it should be something like that:

2020-07-25 22:45:17,178 - [DEBUG] - [GREEN] - __main__ - (main.py).<module>(52) - message

but I get:

2022-03-10 09:47:03,865 - [INFO] - fastapi - (check_service.py).check_service_status(68) - msg

I was trying to add filter to Handlers (there are file and stream ones) and to logger itself, but result is the same. How I should fix it?

The whole code:

import logging
from core.config import settings
import sys


class CustomFilter(logging.Filter):

    COLOR = {
        "DEBUG": "GREEN",
        "INFO": "GREEN",
        "WARNING": "YELLOW",
        "ERROR": "RED",
        "CRITICAL": "RED",
    }

    def filter(self, record):
        record.color = CustomFilter.COLOR[record.levelname]
        return True


logFormatter = logging.Formatter(settings.conf["log_config"]["Format"])
fileHandler = logging.FileHandler(settings.conf["log_config"]["Path"])
fileHandler.setFormatter(logFormatter)
fileHandler.addFilter(CustomFilter())

consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
consoleHandler.addFilter(CustomFilter())

logger = logging.getLogger(__name__)
logger.addFilter(CustomFilter())
logger.addHandler(consoleHandler)
logger.addHandler(fileHandler)
logger.setLevel(settings.conf["log_config"]["Level"])


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source