Skip to content

Formatter Class

Renato Byrro edited this page Feb 16, 2021 · 3 revisions

The http_logging.HttpLogFormatter Class inherits from logstash_async.formatter.LogstashFormatter and provides basic functionality to generalize log messages for any backend (apart from LogStash)[about LogStash inheritance].

Unless you want to change how log messages are formatted[log message anatomy] before sending to your host, you will not need to worry about a Formatter class. As a matter of fact, AsyncHttpHandler already instantiates a default HttpLogFormatter internally.

In case you do want to customize log messages formatting, here are some outlined instructions:

What you want can probably be accomplished by overriding the build_log_message method of the HttpLogFormatter Class:

import logging
from http_logging import AsyncHttpHandler, HttpLogFormatter


# Build your own Log Formatter by inheriting from ours
class MyLogFormatter(HttpLogFormatter):

    # Override method that builds the log message
    def build_log_message(self, record: logging.LogRecord) -> dict:
        return = {
            'hello': 'world',
            'error_level': record.level,
            'error_name': record.name,
            'error_msg': record.msg
            ...
        }

handler = AsyncHttpHandler(
    host='my-domain.com',
    formatter=MyLogFormatter(),  # Override the formatter in Handler args
)

logger = logging.getLogger()
logger.addHandler(handler)

The build_log_message method should take a record argument (an instance of logging.LogRecord) and return a JSON serializable dict.

You will probably want to take some values from record to build your log message. Take a look at the Python documentation ⧉ and check what is available.

Don't worry about including fields passed in the extra argument of your Logger[extra arg], they will be included in the final message.

We advise not to override with the http_logging.HttpLogFormatter.format method. If you do and implement incorrectly, bad things are likely to happen.

Alternatively, take a look at our own http_logging.HttpLogFormatter.build_log_message implementation.

Open an issue in case you need any guidance.


Footnotes

[about LogStash inheritance] Read more about why we inherit from Python LogStash Async in our documentation

[log message anatomy] Please refer to Anatomy of POST requests sent to the HTTP host in the documentation.

[extra arg] Please refer to Logging extra fields in the documentation for more info.

Clone this wiki locally