Description
Structured logging strategy: JSON event schema, level policy, cross-service correlation with requestId.
Logging is debugging in production when you cannot attach a debugger. Every log line must answer: what happened, when, where in the code, and what context surrounded it. Vague logs like 'processing complete' are noise—they waste storage and obscure real signals. LAYER 1 — EVENT STRUCTURE Every log must be a JSON object with at least: timestamp (ISO 8601), level, logger (module:function), message (human-readable summary), requestId (correlation ID across services), and structured context (key-value pairs, never string interpolation). Example: `{"ts":"2025-06-15T14:30:00Z","level":"error","logger":"auth:validateToken","msg":"JWT signature mismatch","requestId":"req_abc123","userId":42,"expectedKid":"key_v2","receivedKid":"key_v1","durationMs":3}` LAYER 2 — LEVEL POLICY - FATAL: process will terminate or is unusable. Immediate paging. ~0.01% of logs. - ERROR: request failed, but process survives. Must have a runbook reference attached. ~0.5%. - WARN: unusual condition, request succeeded with degraded experience (fallback used, cache miss). ~3%. - INFO: business-relevant state transitions. Not every function call—deployments, config reloads, user registrations. ~10%. - DEBUG: developer detail, disabled in production unless troubleshooting a specific user. Off by default, toggle via dynamic config. - TRACE: function entry/exit, SQL queries. Never in production. Dev-only. LAYER 3 — CORRELATION Every request gets a unique requestId (UUID v4) at the API gateway. Pass it via HTTP header (X-Request-Id) and thread-local context. Async tasks keep the originating requestId. Downstream services propagate it. Every log line in the chain carries the same requestId so you can grep across 12 microservices for one user's journey. LAYER 4 — PITFALLS - Logging PII (emails, IPs, credit cards) breaches compliance. Hash or redact sensitive fields. - Logging inside hot loops (N=10k per request) kills throughput. Sample or aggregate. - Logging before validation. If the input is garbage, log it—silently dropping invalid input is a debugging hell. - Over-logging at ERROR. If every minor failure is ERROR, real errors drown in noise. OUTPUT: JSON schema for log events, level policy table, correlation trace with annotated example.
No comments yet. Be the first!