CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-json-logger

JSON formatter for Python's built-in logging package that enables structured, machine-readable log output

Pending
Overview
Eval results
Files

json-formatting.mddocs/

Standard JSON Formatting

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.

Core Imports

from pythonjsonlogger.json import JsonFormatter, JsonEncoder

For type checking:

from typing import Union, Callable, Optional, Any
import json

Capabilities

JsonFormatter Class

Main 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
        """

JsonEncoder Class

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
        """

Deprecated Module Access

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 warning

Usage Examples

Basic JSON Formatter Setup

import 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"})

Custom JSON Encoder

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
)

Custom Serializer Options

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
)

Custom Default Function

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
)

Type Handling

The JsonEncoder automatically handles these Python types:

  • datetime.datetime, datetime.date, datetime.time: Converted to ISO format strings
  • Exception objects: Converted to "ExceptionClass: message" format
  • Traceback objects: Converted to formatted traceback strings
  • Enum objects: Converted to their values
  • bytes/bytearray: Converted to base64 strings
  • dataclass instances: Converted to dictionaries
  • type objects: Converted to class names
  • Unknown types: Fallback to str() or repr(), or "could_not_encode"

Install with Tessl CLI

npx tessl i tessl/pypi-python-json-logger

docs

core-configuration.md

index.md

json-formatting.md

performance-formatting.md

type-handling.md

utilities.md

tile.json