Structured JSON Logging Setup

Configure a JSON formatter so every log record carries consistent fields, making logs searchable and correlatable across services.

PythonResilience

Code

pythonsnippet
26 lines
import json
import logging
import sys
from datetime import datetime, timezone


class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = {
            "level": record.levelname,
            "message": record.getMessage(),
            "logger": record.name,
            "timestamp": datetime.now(timezone.utc).isoformat(),
        }
        if record.exc_info:
            payload["exception"] = self.formatException(record.exc_info)
        return json.dumps(payload)


def configure_logging(level: str = "INFO") -> logging.Logger:
    logger = logging.getLogger("app")
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(JsonFormatter())
    logger.addHandler(handler)
    logger.setLevel(level)
    return logger

How the snippet works

Count the class JsonFormatter and the functions format and configure_logging as the entire surface area of Structured JSON Logging Setup.

datetime, timezone are the only symbols borrowed from logging — the coupling is explicit and narrow.

What to watch for

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

Applying it

The main signature reads def format(self, record: logging.LogRecord) -> str

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

Statements that matter

def configure_logging(level: str = "INFO") -> logging.Logger:
    logger = logging.getLogger("app")
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(JsonFormatter())
    logger.addHandler(handler)
    logger.setLevel(level)
    return logger

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `logging` must be present in the project or the import fails at load time.