Intercept Python Logging

Reading time ~1 minute

The problem:

I need to ship specific log record and had formatter written in python. It is pretty complex transformation.

I thought of using Logstash but I then need to either convert this python logic or write a plugin to use already written python parser. Plus I need to install logstash… I wanted a simpler solution

How to solve it

Use custom python logging Handler and Filter!

import logging

messages = []
logger = logging.getLogger(__name__)

class ListenFilter(logging.Filter):

    def filter(self, record):
        """Determine which log records to output.
        Returns 0 for no, nonzero for yes.
        if record.getMessage().startswith('dont: '):
            return False
        return True

class RequestsHandler(logging.Handler):
    def emit(self, record):
        """Send the log records (created by loggers) to
        the appropriate destination.

handler = RequestsHandler()

filter_ = ListenFilter()

# log I want"logme: Howdy!")

# log i want to skip"dont: I'm doing great!")

# prints ['logme: Howdy!']



Great tools to decided refnanice Continue reading

Smile every time you sudo

Published on February 18, 2021

Don't let your money sleep

Published on December 20, 2020