slog handlers, attributes, log levels, request IDs, and JSON logs for collectors.
7 min readGo for SREBuild
slog Overview
slog is Go's structured logging library (Go 1.21+). It provides a fast, flexible API for structured logging with handlers that output JSON, text, or custom formats.
Goslog-basics.go
26 linesLn 1, Col 1Go
slog.Info and slog.Error log with key-value attributes. slog.Group organizes related attributes. Typed attributes (slog.String, slog.Int) are faster than string formatting. slogs default handler outputs text.
Handlers
Gohandler-configuration.go
32 linesLn 1, Col 1Go
slog.NewTextHandler outputs human-readable text. slog.NewJSONHandler outputs JSON for log collectors. AddSource adds file and line numbers. ReplaceAttr transforms attribute names and values.
Attributes and Groups
Goattribute-patterns.go
38 linesLn 1, Col 1Go
Typed attributes avoid reflection and string formatting. slog.Group organizes related attributes. slog.With creates a logger with pre-set attributes. Context integration passes request-scoped values to loggers.
Log Levels
Golog-level-configuration.go
36 linesLn 1, Col 1Go
slog provides four levels: Debug, Info, Warn, Error. slog.LevelVar allows dynamic level changes. Set level from environment variable for deployment flexibility. Debug is verbose — use only in development.
Request IDs
Gorequest-id-propagation.go
41 linesLn 1, Col 1Go
Request IDs trace requests across services. Generate or extract from headers. Store in context for propagation. Add to logger for automatic inclusion in all log messages. Set response header for client correlation.
JSON Logs for Collectors
Goproduction-json-logging.go
37 linesLn 1, Col 1Go
JSON logs are machine-readable and parseable by log collectors. Standardize field names for consistent parsing. Include source location for debugging. Group related fields for clarity. Use timestamps in RFC3339 format.
Use structured logging from day one
Structured logs are easier to search, filter, and analyze. Start with slog and JSON output. The performance overhead is minimal compared to fmt.Println. Your future self will thank you when debugging production issues.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.