JSON Logging for Python

1.5.1 · active · verified Sun Apr 12

json-logging is a Python library that enables structured JSON logging for your applications. It provides a `JSONLogFormatter` that outputs log records as JSON objects, making them easier to consume by log management systems like ELK stack. The library is actively maintained, with the current stable version being 1.5.1, and receives regular updates to address issues and add framework support.

Warnings

Install

Imports

Quickstart

Initializes JSON logging for your application and demonstrates how to log standard messages and messages with extra fields. The `init_json_logging` function configures the root logger (or a specific logger if provided) to use the `JSONLogFormatter`. Messages are output as JSON objects to `stdout` by default.

import logging
import json_logging
import sys

# Initialize JSON logging early in your application lifecycle
json_logging.init_json_logging(enable_json=True)

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

# Ensure the handler is using the JSON formatter
# json_logging.init_json_logging typically handles this for the root logger
# or its own default handler. For custom handlers, ensure they use JSONLogFormatter.
# For example:
# handler = logging.StreamHandler(sys.stdout)
# handler.setFormatter(json_logging.JSONLogFormatter())
# logger.addHandler(handler)

logger.info('This is a basic info log message.')
logger.warning('A warning occurred!', extra={'event_id': 'WARN-001', 'user': 'test_user'})

try:
    1 / 0
except ZeroDivisionError as e:
    logger.error('An error occurred during division.', exc_info=True, extra={'operation': 'math', 'error_type': str(type(e))})

print('\n--- Example Output (trimmed for brevity) ---\n')
# To see output, run this script.

view raw JSON →