JSON Formatter
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
- gotcha This `jsonformatter` library (by MyColorfulDays, version 0.3.4) is distinct from `python-json-logger` (by madzak/nhairs), which is a more widely used and actively maintained alternative with a similar purpose. Users often confuse the two. If you're looking for the commonly recommended JSON logger, you might be looking for `python-json-logger`.
- gotcha When logging objects that are not natively JSON serializable (e.g., custom class instances, `datetime` objects without special handling), `jsonformatter` may raise `TypeError` unless a custom `default` or `cls` parameter is provided to the `JsonFormatter` constructor. This is a common pitfall in Python's `json` module usage.
- deprecated While `jsonformatter` officially supports Python 2.7, Python 2 has reached its End-of-Life (EOL) and is no longer maintained. Using it in new projects or maintaining existing Python 2 projects carries security and compatibility risks.
Install
-
pip install jsonformatter
Imports
- basicConfig
from jsonformatter import basicConfig
- JsonFormatter
from jsonformatter import JsonFormatter
Quickstart
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.')