Stage 3 · Build
Production-Ready Services
Structured Logging
Emit JSON logs with slog or zap, attach request IDs, fields, levels, and error context.
Why Structured Logs
Unstructured log lines like 'user logged in' are hard to search and parse. Structured logs emit JSON with named fields. This enables filtering, alerting, and analytics on log data.
log/slog
Fields and Context
Log Levels
| Level | Use Case | Example |
|---|---|---|
| Debug | Detailed diagnostic information | SQL query, request headers |
| Info | Normal operation events | Request completed, job finished |
| Warn | Potential problems | Slow query, high memory usage |
| Error | Failures requiring attention | Database connection failed, job failed |
Error Logging
Log Aggregation
- stdout/stderr: Docker and Kubernetes collect container logs.
- File-based: Use log rotation with lumberjack or similar.
- Centralized: Ship to Datadog, ELK, or CloudWatch.
- Structured JSON: Enables parsing and querying.
In containerized environments, always log to stdout. Docker and Kubernetes capture stdout automatically. Do not write to files inside containers.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.