Logstash Python Formatter

0.1.2 · maintenance · verified Thu Apr 16

This library provides a Python logging formatter designed to output log data as JSON objects compatible with Logstash json filters. It enables standard Python logging to produce structured logs that can be easily ingested and parsed by Logstash. The current version is 0.1.2, released in 2018, indicating a low or inactive release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the standard Python logging module to use `LogstashFormatterV1`. It sets up a basic logger with a stream handler, applies the formatter, and shows examples of logging simple messages, messages with extra fields, and exceptions, all formatted as JSON. The `LogstashFormatterV1` handles conversion of `msg` to `@message` and integrates `extra` dictionary fields.

import logging
from logstash_formatter import LogstashFormatterV1
import sys

# Configure a logger
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)

# Create a StreamHandler to output logs to console
handler = logging.StreamHandler(sys.stdout)

# Create an instance of LogstashFormatterV1
# You can pass 'fmt' as a JSON string to add default extra fields or override source_host
# For example: formatter = LogstashFormatterV1(fmt='{"extra": {"service": "my-service"}}')
formatter = LogstashFormatterV1()

# Set the formatter for the handler
handler.setFormatter(formatter)

# Add the handler to the logger
logger.addHandler(handler)

# Log messages
logger.info('This is a simple info message.')
logger.warning('This is a warning message with some context.', extra={'user_id': 123, 'transaction_id': 'abc-123'})

try:
    1 / 0
except ZeroDivisionError:
    logger.error('An error occurred!', exc_info=True, extra={'error_code': 500})

# Logging a dictionary directly as a message (fields are merged into the top level)
logger.info({'event': 'user_login', 'username': 'testuser'})

view raw JSON →