Stage 1 · Code
Testing & Debugging in Go
Debugging With Logs
Use structured logging with log/slog to add context to failures without hiding root causes.
log/slog: Structured Logging
log/slog (added in Go 1.21) is the standard structured logger. It emits log records with key-value attributes, making logs searchable in aggregation systems like Loki or CloudWatch.
Levels and Handlers
Levels filter noise: DEBUG during development, INFO in production, WARN for degraded-but-running states, ERROR for failures requiring attention.
Adding Context
Use slog.With to create a logger pre-populated with attributes. Pass it through your call stack so every log line carries the request ID, user, or trace context.
Temporary Trace Logging
Use slog.Debug for temporary investigative logging. Debug lines are free in production (filtered before the handler runs) and visible during development.
The old log.Printf prints to stderr without structure and cannot be filtered by level. Migrate to slog in new code. Structured logs are searchable, parseable, and can be enriched by your logging infrastructure without any code changes.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.