0Pricing
Python Academy · Lesson

Structured Logging

Emit JSON-formatted logs for machine-readable output.

What Is Structured Logging?

Structured logging emits log records as machine-readable data (JSON) instead of free-form text, making them easy to index, search, and alert on.

import logging, json

def log_json(level, msg, **kw):
    record = {"level": level, "msg": msg, **kw}
    print(json.dumps(record))

log_json("INFO", "Request received", path="/api/users", method="GET")

Custom JSON Formatter

Subclass logging.Formatter to emit JSON instead of plain text.

import logging, json

class JSONFormatter(logging.Formatter):
    def format(self, record):
        return json.dumps({
            "time": self.formatTime(record),
            "level": record.levelname,
            "name": record.name,
            "msg": record.getMessage(),
        })

handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
logging.getLogger().addHandler(handler)

All lessons in this course

  1. The logging Module Basics
  2. Handlers, Formatters, and Filters
  3. Structured Logging
  4. Debugging with pdb
← Back to Python Academy