Python: Writing custom log handler and formatter

Log Handlers dictate how the log entries are handled. For example FileHandler would allow us to pipe our logs to a file. HTTP Handler makes it possible to send the logs over HTTP to a remote server. We can write our own log handlers if we need to customize the way our logs are processed. Writing a custom handler is pretty simple. We have to subclass it from logging.Handler class and must define the emit method. This method is called with each log record so we can process it.

Here’s an exmaple of a custom log handler which POSTs the logs to a remote server using the popular requests library.

Now we have our custom handler that will post the logs to another server. What if we want to send the message in a specific format? We write our custom formatter. A formatter has a format method which gets the record. We can take the record and return a message formatted according our need. Here’s an example for logstash format:

So we have got ourselves a custom log handler and a formatter. But how do we use them? Here’s a short code snippet:

3 Comments Python: Writing custom log handler and formatter

  1. ashish

    how can i create custom logger function like we have default functions –

    i want to create simple like below


  2. Matthew

    I had to add Handler.__init__(self) to the __init__() method of RequestsHandler to get this to work:

    class RequestsHandler(Handler):
        def __init__(self):
        def emit(self, record):
            log_entry = self.format(record)
                                 log_entry, headers={“Content-type”: “application/json”}).content


Leave a Reply

Your email address will not be published. Required fields are marked *