301 — Structured Logging for Observability

Intermediate

Learn why structured JSON logs are essential for observability, how to include trace context for correlation, and how to configure logging levels, context propagation, and the OpenTelemetry log bridge API.

Learning Objectives

1
Implement structured JSON logging in a Node.js application
2
Include trace context (trace_id, span_id) in log entries
3
Configure log levels appropriately for each environment
4
Understand OTel log bridge API capabilities
Step 1

Why structured logs beat plain text

Compare plain text logs with structured JSON logs and understand why structured logging is non-negotiable for production observability.

Commands to Run

cat <<'EOF'
--- PLAIN TEXT LOG (bad) ---
2024-03-15 10:30:00 ERROR Failed to process order 12345 for user john@example.com

--- STRUCTURED JSON LOG (good) ---
{"timestamp":"2024-03-15T10:30:00Z","level":"error","message":"Failed to process order","order_id":12345,"user_id":"john@example.com","service":"order-api","trace_id":"a1b2c3d4e5f6","span_id":"f6e5d4c3b2a1","error":"payment_declined"}

--- WHY STRUCTURED WINS ---
1. Machine-parseable: filter by any field
2. Consistent schema: no regex needed
3. Correlation: trace_id links logs to traces
4. Aggregation: count errors by service, user, type
EOF

What This Does

Plain text logs require fragile regex parsing and make it nearly impossible to filter or aggregate at scale. Structured JSON logs have explicit fields that log aggregation systems like Loki can index and query directly. Every field becomes a dimension you can filter, group, and alert on.

Expected Outcome

You see the contrast between a plain text log line and a structured JSON log line, followed by four reasons structured logging wins.

Pro Tips

  • 1
    If you inherit a codebase with plain text logs, migrate to structured logging as your first observability improvement
  • 2
    Most logging libraries support structured output with a single config change
Was this step helpful?

All Steps (0 / 10 completed)