logging-json

0.6.0 · active · verified Fri Apr 17

logging-json is a Python library that provides a JSON formatter for the standard `logging` module, allowing applications to output logs in a structured JSON format. This is particularly useful for centralized logging systems and machine readability. The current version is 0.6.0, and it generally maintains an active release cadence with periodic updates for bug fixes and new features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic logger with `logging-json`. It configures a `StreamHandler` to output JSON formatted logs to standard output. It also shows how to include extra dictionary fields in your logs, which are automatically merged into the root JSON object.

import logging
from logging_json import JSONFormatter
import sys

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

# Create a stream handler (e.g., to stdout)
handler = logging.StreamHandler(sys.stdout)

# Create a JSON formatter instance
# Optional: Customize indentation, ASCII encoding, or datetime format
formatter = JSONFormatter(
    json_indent=2, # Pretty-print JSON
    json_ensure_ascii=False, # Allow non-ASCII characters directly
    datetime_format="%Y-%m-%dT%H:%M:%S%z" # Custom datetime format with timezone
)

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

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

# Log messages with standard fields and extra context
logger.info("This is an info message.")
logger.warning("Something potentially bad happened.", extra={"user_id": 123, "session": "abc"})

try:
    raise ValueError("Example error")
except ValueError:
    # logger.exception automatically includes traceback
    logger.exception("An error occurred during processing.")

logger.debug("This message will not be shown as level is INFO.")

view raw JSON →