JSON formatter for Python's built-in logging package that enables structured, machine-readable log output
—
JSON formatting using Python's built-in json module with custom encoder support for handling extended Python types. This is the default and most compatible formatter.
from pythonjsonlogger.json import JsonFormatter, JsonEncoderFor type checking:
from typing import Union, Callable, Optional, Any
import jsonMain JSON formatter using Python's standard library json module for serialization.
class JsonFormatter(BaseJsonFormatter):
def __init__(
self,
*args,
json_default: OptionalCallableOrStr = None,
json_encoder: OptionalCallableOrStr = None,
json_serializer: Union[Callable, str] = json.dumps,
json_indent: Optional[Union[int, str]] = None,
json_ensure_ascii: bool = True,
**kwargs,
) -> None:
"""
Standard JSON formatter initialization.
Parameters:
- args: see BaseJsonFormatter
- json_default: function for encoding non-standard objects
- json_encoder: custom JSON encoder class
- json_serializer: json.dumps-compatible callable for serialization
- json_indent: indent parameter for json_serializer
- json_ensure_ascii: ensure_ascii parameter for json_serializer
- kwargs: see BaseJsonFormatter
"""
def jsonify_log_record(self, log_record: LogRecord) -> str:
"""
Convert log record to JSON string.
Parameters:
- log_record: dictionary containing log data
Returns:
JSON string representation of the log record
"""Custom JSON encoder that extends json.JSONEncoder to handle additional Python types.
class JsonEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
"""
Override default serialization for non-standard types.
Handles datetime objects, exceptions, tracebacks, enums, bytes,
dataclasses, type objects, and unknown types.
Parameters:
- o: object to serialize
Returns:
Serializable representation of the object
"""
def format_datetime_obj(self, o: datetime.time | datetime.date | datetime.datetime) -> str:
"""
Format datetime objects for JSON serialization.
Parameters:
- o: datetime object to format
Returns:
ISO format string representation
"""The json module supports deprecated access to constants from other modules for backward compatibility.
# Deprecated - use pythonjsonlogger.core.RESERVED_ATTRS instead
from pythonjsonlogger.json import RESERVED_ATTRS # Issues deprecation warningimport logging
from pythonjsonlogger.json import JsonFormatter
# Create logger with JSON formatter
logger = logging.getLogger('my_app')
handler = logging.StreamHandler()
formatter = JsonFormatter('%(levelname)s %(name)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# Log with extra fields
logger.info("User logged in", extra={"user_id": 123, "ip": "192.168.1.1"})import json
from pythonjsonlogger.json import JsonFormatter, JsonEncoder
class CustomEncoder(JsonEncoder):
def format_datetime_obj(self, o):
# Custom datetime formatting
return o.strftime('%Y-%m-%d %H:%M:%S UTC')
# Use custom encoder
formatter = JsonFormatter(
'%(levelname)s %(message)s',
json_encoder=CustomEncoder
)from pythonjsonlogger.json import JsonFormatter
import json
# Pretty-printed JSON with custom options
formatter = JsonFormatter(
'%(levelname)s %(name)s %(message)s',
json_indent=2,
json_ensure_ascii=False,
json_serializer=json.dumps
)from pythonjsonlogger.json import JsonFormatter
import decimal
def custom_default(obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
raise TypeError(f"Object {obj} is not JSON serializable")
formatter = JsonFormatter(
'%(levelname)s %(message)s',
json_default=custom_default
)The JsonEncoder automatically handles these Python types:
Install with Tessl CLI
npx tessl i tessl/pypi-python-json-logger