PYTHON Contents

Structured Logging (Fields, Correlation IDs)

Use structured logging patterns (stable key=value fields) so logs are searchable, correlatable, and actionable during incidents.

On this page

Structured Logging Mindset

Logs should be machine-searchable. Prefer stable fields (event, request_id, user_id, latency_ms) over free-form sentences.

Key=Value Pattern

import logging

logger = logging.getLogger("myapp")

def log_request(request_id: str, user_id: int, path: str, elapsed_ms: float) -> None:
    logger.info(
        "event=request request_id=%s user_id=%s path=%s elapsed_ms=%.2f",
        request_id, user_id, path, elapsed_ms
    )

Correlation Fields

  • request_id / trace_id for distributed correlation
  • user_id or anonymized identifiers for support
  • elapsed_ms and result status

Operational Checklist

  • Define a minimum logging schema (required fields per event type).
  • Never log secrets; mask tokens and credentials.
  • Keep messages stable; changing field names breaks dashboards.

Failure Modes

  • Unsearchable logs: free text prevents aggregation and alerting.
  • PII leakage: sensitive data ends up in centralized log storage.