JSON Log Formatter

1.1.1 · active · verified Thu Apr 09

The `json-log-formatter` library provides a Python logging formatter that outputs log records as JSON strings. This structured logging approach facilitates easier integration with log aggregation and analysis systems like Logstash or ElasticSearch. The library is currently at version 1.1.1 and appears to be actively maintained, with regular updates to support modern Python logging practices.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic logger using `JSONFormatter` to output structured JSON logs to standard output. It shows logging of informational messages with custom `extra` fields and how exceptions are handled.

import logging
import sys
from json_log_formatter import JSONFormatter

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

# Create a JSON formatter instance
formatter = JSONFormatter()

# Create a StreamHandler that writes to stdout
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)

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

# Log some messages
logger.info('User signed up', extra={'user_id': 123, 'email': 'test@example.com'})
logger.warning('Payment failed', extra={'order_id': 'abc-123', 'reason': 'card declined'})

try:
    raise ValueError('Something went wrong!')
except ValueError:
    logger.error('An unexpected error occurred', exc_info=True, extra={'transaction_id': 'xyz-456'})

view raw JSON →