JSON Log Formatter
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
- gotcha As of v0.3.0, the formatter attempts a 'best effort' to serialize log records containing non-serializable values (e.g., WSGIRequest objects) instead of raising a TypeError. While this prevents crashes, it might result in altered or omitted data for those specific fields if not explicitly handled.
- gotcha When using alternative JSON libraries like `ujson` or `simplejson` (by overriding `JSONFormatter.json_serializer`), be aware that `ujson` specifically does not support the `json.dumps(default=f)` argument. This can lead to `TypeError` exceptions or silently skipped attributes if objects cannot be serialized directly.
- gotcha To add custom fields to every log record (e.g., user ID, IP address) or to customize the serialization of specific object types (e.g., `datetime` objects to timestamps), you must override the `json_record()` method in a custom formatter subclass. Not doing so will prevent these customizations from appearing in your logs.
- gotcha Logging sensitive data (e.g., passwords, API keys, PII) in JSON logs is a significant security risk. JSON's flexible structure makes it easy to accidentally include more data than intended, which can violate privacy regulations.
Install
-
pip install json-log-formatter
Imports
- JSONFormatter
from json_log_formatter import JSONFormatter
- VerboseJSONFormatter
from json_log_formatter import VerboseJSONFormatter
- FlatJSONFormatter
from json_log_formatter import FlatJSONFormatter
Quickstart
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'})