Logging with slog
Use `log/slog` for structured logs with stable keys, contextual attributes, and clear handler boundaries.
Canonical guidance
- prefer structured keys over free-form concatenated log lines
- attach stable request or job context with
With - keep handler setup in a narrow composition layer
Use when
- service logs
- request tracing context
- machine-consumable log pipelines
Avoid
- interpolated blob strings with no stable fields
- repeating the same attributes at every call site
- hiding logger construction deep inside business logic
Preferred pattern
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With(
slog.String("service", "api"),
)
logger.Info("request complete", slog.Int("status", http.StatusOK))
Anti-pattern
- unstructured printf logs in code paths that need machine-readable diagnostics
Explanation: This anti-pattern is tempting because printf is fast to type, but it throws away the structured context operators depend on.
Why
- structured logs are easier to query, aggregate, and correlate
Related pages
Sources
- log/slog package - Go Team
- Structured Logging with slog - Jonathan Amsterdam