or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-configuration.mdindex.mdjson-formatting.mdperformance-formatting.mdtype-handling.mdutilities.md
tile.json

tessl/pypi-python-json-logger

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-json-logger@3.3.x

To install, run

npx @tessl/cli install tessl/pypi-python-json-logger@3.3.0

index.mddocs/

Python JSON Logger

A JSON formatter for Python's built-in logging package that enables structured, machine-readable log output. Python JSON Logger integrates seamlessly with Python's standard logging framework and supports multiple JSON serialization backends for optimal performance and compatibility.

Package Information

  • Package Name: python-json-logger
  • Language: Python
  • Installation: pip install python-json-logger

Core Imports

import pythonjsonlogger
from pythonjsonlogger.json import JsonFormatter

Common alternative imports for specific formatters:

# Standard JSON formatter
from pythonjsonlogger.json import JsonFormatter

# High-performance orjson formatter (optional dependency)
from pythonjsonlogger.orjson import OrjsonFormatter

# High-performance msgspec formatter (optional dependency)
from pythonjsonlogger.msgspec import MsgspecFormatter

Deprecated imports (still functional but issue warnings):

# Deprecated - use pythonjsonlogger.json instead
from pythonjsonlogger.jsonlogger import JsonFormatter, JsonEncoder

Basic Usage

import logging
from pythonjsonlogger.json import JsonFormatter

# Set up JSON logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# Create console handler with JSON formatter
handler = logging.StreamHandler()
formatter = JsonFormatter('%(levelname)s %(name)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Log messages are now JSON formatted
logger.info("This is a test message", extra={"user_id": 123, "action": "login"})
# Output: {"levelname": "INFO", "name": "root", "message": "This is a test message", "user_id": 123, "action": "login"}

# Log structured data directly
logger.info({"event": "user_action", "user_id": 456, "action": "logout"})
# Output: {"event": "user_action", "user_id": 456, "action": "logout"}

Architecture

Python JSON Logger extends Python's standard logging framework with JSON serialization capabilities:

  • BaseJsonFormatter: Abstract base class providing core JSON logging functionality and configuration
  • Formatter Implementations: Concrete formatters using different JSON backends (json, orjson, msgspec)
  • Type Handling System: Extensible default functions for serializing complex Python types
  • Configuration Options: Field renaming, static fields, timestamp handling, and custom serialization

The modular design allows choosing optimal JSON backends while maintaining consistent logging behavior across applications.

Capabilities

Standard JSON Formatting

JSON formatting using Python's built-in json module with custom encoder support for extended type handling.

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
    ): ...

class JsonEncoder(json.JSONEncoder):
    def default(self, o: Any) -> Any: ...
    def format_datetime_obj(self, o: datetime.time | datetime.date | datetime.datetime) -> str: ...

Standard JSON Formatting

High-Performance Formatting

Alternative JSON formatters using orjson and msgspec for improved performance in high-throughput applications.

class OrjsonFormatter(BaseJsonFormatter):
    def __init__(
        self,
        *args,
        json_default: OptionalCallableOrStr = orjson_default,
        json_indent: bool = False,
        **kwargs
    ): ...

class MsgspecFormatter(BaseJsonFormatter): 
    def __init__(
        self,
        *args,
        json_default: OptionalCallableOrStr = msgspec_default,
        **kwargs
    ): ...

High-Performance Formatting

Core Configuration

Base formatter class and configuration options for customizing JSON log output including field management, formatting, and serialization control.

class BaseJsonFormatter(logging.Formatter):
    def __init__(
        self,
        fmt: Optional[str] = None,
        datefmt: Optional[str] = None,
        style: str = "%",
        validate: bool = True,
        *,
        prefix: str = "",
        rename_fields: Optional[Dict[str, str]] = None,
        rename_fields_keep_missing: bool = False,
        static_fields: Optional[Dict[str, Any]] = None,
        reserved_attrs: Optional[Sequence[str]] = None,
        timestamp: Union[bool, str] = False,
        defaults: Optional[Dict[str, Any]] = None,
        exc_info_as_array: bool = False,
        stack_info_as_array: bool = False
    ): ...

Core Configuration

Type Handling

Functions for serializing complex Python types including datetimes, exceptions, dataclasses, enums, UUIDs, bytes, and custom objects.

def unknown_default(obj: Any) -> str: ...
def datetime_any(obj: datetime.time | datetime.date | datetime.datetime) -> str: ...
def time_default(obj: datetime.time) -> str: ...
def date_default(obj: datetime.date) -> str: ...
def datetime_default(obj: datetime.datetime) -> str: ...
def exception_default(obj: BaseException) -> str: ...
def traceback_default(obj: TracebackType) -> str: ...
def dataclass_default(obj) -> dict[str, Any]: ...
def enum_default(obj: enum.Enum | enum.EnumMeta) -> Any | list[Any]: ...
def uuid_default(obj: uuid.UUID) -> str: ...
def bytes_default(obj: bytes | bytearray, url_safe: bool = True) -> str: ...
def type_default(obj: type) -> str: ...

Type Handling

Utilities

Helper functions for package management and compatibility checking.

def package_is_available(
    name: str, 
    *, 
    throw_error: bool = False, 
    extras_name: str | None = None
) -> bool: ...

Utilities

Types

from typing import Optional, Union, Callable, List, Dict, Container, Any, Sequence

# Type aliases
OptionalCallableOrStr = Optional[Union[Callable, str]]
LogRecord = Dict[str, Any]

# Exception classes
class PythonJsonLoggerError(Exception):
    """Generic base class for all Python JSON Logger exceptions"""

class MissingPackageError(ImportError, PythonJsonLoggerError):
    """A required package is missing"""
    def __init__(self, name: str, extras_name: str | None = None) -> None: ...

# Constants
RESERVED_ATTRS: List[str]  # Default reserved LogRecord attributes
ORJSON_AVAILABLE: bool     # Whether orjson is available
MSGSPEC_AVAILABLE: bool    # Whether msgspec is available