JSON Formatter

0.3.4 · active · verified Wed Apr 15

jsonformatter is a Python library that provides a logging formatter to output log records as JSON objects. It allows for easy customization of LogRecord attributes, enabling users to include or replace fields, for instance, to integrate with log aggregation systems like Logstash. It supports Python 2.7 and Python 3. The latest version, 0.3.4, was released in November 2024, with an irregular but ongoing release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates two ways to use `jsonformatter`: first, using `basicConfig` for a quick setup, and second, by creating a `JsonFormatter` instance with a custom format string and attaching it to a `StreamHandler`. It also shows how to include extra fields in log messages and handle exceptions.

import logging
from jsonformatter import basicConfig, JsonFormatter
import sys

# Basic configuration for JSON output to console
basicConfig(level=logging.INFO)
logging.info('Hello, jsonformatter basic config!')

# Example with custom formatter and fields
FORMAT_STRING = '''{
    "time": "asctime",
    "level": "levelname",
    "message": "message",
    "logger_name": "name",
    "process_id": "process"
}'''

logger = logging.getLogger('my_app')
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
formatter = JsonFormatter(FORMAT_STRING)
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info('User logged in', extra={'user_id': 123, 'ip_address': '192.168.1.1'})
try:
    raise ValueError('Something went wrong')
except ValueError:
    logger.exception('An error occurred during processing.')

view raw JSON →