serhii.net

In the middle of the desert you can say anything you want

07 Dec 2023

Python filtering logging logs and warnings

Filtering logging messages in Python

class LoggingFilter(logging.Filter):
    def filter(self, record):
        if "Connection pool is full" in record.getMessage():
            return False

logger_cpool = logging.getLogger("urllib3.connectionpool")
logger_cpool.addFilter(LoggingFilter())
  • All filters are applied until one returns False, then the record is silenced, otherwise it gets logged normally.
  • Any magic can be done, incl. regex etc.!
  • LogRecord attributes1 had a logrecord.message but I didn’t have it in my case (todo), but I found getMessage().

Getting the name of your logger to apply the filter to

How to list all existing loggers using python.logging module - Stack Overflow:

import logging

loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]

Warnings

Temporarily supressing warnings

warnings — Warning control — Python 3.12.0 documentation:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

Dealing with warnings through logging

logging — Logging facility for Python — Python 3.12.0 documentation

# capture is True for enabling, False for disabling
logging.captureWarnings(capture)

# all warnings will become logs from logger 'py.warnings' with severity WARN
Nel mezzo del deserto posso dire tutto quello che voglio.