Structured Log JSON Formatter

Format Python log records as single-line JSON with extra fields, making logs machine-parsable without losing context.

PythonResilience

Code

pythonsnippet
27 lines
import json
import logging

RESERVED = {'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename',
            'module', 'exc_info', 'exc_text', 'stack_info', 'lineno', 'funcName',
            'created', 'msecs', 'relativeCreated', 'thread', 'threadName',
            'processName', 'process', 'taskName'}

class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = {
            'level': record.levelname,
            'message': record.getMessage(),
            'logger': record.name,
            'time': self.formatTime(record, '%Y-%m-%dT%H:%M:%S'),
        }
        for key, value in record.__dict__.items():
            if key not in RESERVED and not key.startswith('_'):
                payload[key] = value
        if record.exc_info:
            payload['exception'] = self.formatException(record.exc_info)
        return json.dumps(payload, ensure_ascii=False, default=str)

def configure() -> None:
    handler = logging.StreamHandler()
    handler.setFormatter(JsonFormatter())
    logging.basicConfig(level=logging.INFO, handlers=[handler])

How it works

The working surface is the class JsonFormatter and the functions format and configure — everything else is wiring.

Iteration happens inside for key, value in record.__dict__.items() — everything outside it runs once.

Watch out for

  • Plan for an install step: logging is a real dependency, resolved by the package manager.

Using it

The entry-point signature is def format(self, record: logging.LogRecord) -> str

format is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def configure() -> None:
    handler = logging.StreamHandler()
    handler.setFormatter(JsonFormatter())
    logging.basicConfig(level=logging.INFO, handlers=[handler])

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `logging`. Add it to your project before running the snippet.