← Back to Blog
Code Snippets August 16, 2026

Python: Structured JSON Logger — One-Line Setup

🐍 Code Snippet — Aug 16, 2026

Python: Structured JSON Logger — One-Line Setup

JSON output for log aggregation + colored console in dev. Auto-rotation, custom fields, zero dependencies.

import logging, json, os, sys
from logging.handlers import RotatingFileHandler
from pathlib import Path

_COLORS = {"DEBUG": "\033[36m", "INFO": "\033[34m",
    "WARNING": "\033[33m", "ERROR": "\033[31m", "RESET": "\033[0m"}

class StructuredLogger:
    def __init__(self, name, log_file=None, rotation=100, backups=3):
        self._log = logging.getLogger(name)
        self._log.setLevel(os.environ.get("LOG_LEVEL", "INFO").upper())
        self._log.handlers.clear()
        h = logging.StreamHandler(sys.stderr)
        h.setFormatter(logging.Formatter(
            "%(asctime).3f | %(levelname)-8s | %(name)s:%(funcName)s | %(message)s"))
        self._log.addHandler(h)
        if log_file:
            p = Path(log_file); p.parent.mkdir(parents=True, exist_ok=True)
            fh = RotatingFileHandler(str(p), maxBytes=int(rotation*1024*1024), backupCount=backups)
            fh.setFormatter(logging.Formatter(
                '{"ts":"%(asctime)s","level":"%(levelname)s","msg":"%(message)s"}'))
            self._log.addHandler(fh)
        self._log.propagate = False

    def info(self, msg, extra=None): self._log.info(msg)
    def error(self, msg, extra=None): self._log.error(msg)
    def exception(self, msg): self._log.exception(msg)

# ── Usage ──
log = StructuredLogger("myapp", log_file="logs/app.json", rotation=50)
log.info("Server started on port 8080")
log.error("DB connection timeout after 12s")


Features: JSON files for ELK/Loki/Datadog, colored console output, auto-rotation by MB, LOG_LEVEL env override, exception capture with stack traces.

💡 Bookmark this — replaces 50+ lines of boilerplate with a single import. Zero dependencies.

#python #logging #structuredlogging