Design structured slog attributes and request IDs
Design structured slog attributes and request IDs
An operational log records an event with stable fields that a machine can filter. Use slog with a JSON handler, a consistent message, severity, service and operation attributes, and a request ID for correlation. Generate or validate IDs at the trust boundary; an ID is not a credential. Prefer an allowlist of fields rather than logging request headers or bodies.
package main
import ( "bytes" "encoding/json" "fmt" "log/slog")
func main() { var b bytes.Buffer l := slog.New(slog.NewJSONHandler(&b, nil)).With("service", "catalog", "request_id", "r-17") l.Info("completed", "status", 200) var m map[string]any if err := json.Unmarshal(b.Bytes(), &m); err != nil { panic(err) } fmt.Println(m["service"], m["request_id"], m["status"])}With creates a derived logger carrying shared attributes; the parent is unchanged. Decode JSON rather than comparing timestamps or field ordering. In a real handler attach the ID once and pass the logger explicitly. Do not copy passwords, tokens or arbitrary user data into attributes.
Expected output:
catalog r-17 200Control severity without changing call sites
package main
import ( "bytes" "fmt" "log/slog")
func main() { var b bytes.Buffer var level slog.LevelVar l := slog.New(slog.NewJSONHandler(&b, &slog.HandlerOptions{Level: &level})) l.Debug("detail") fmt.Println(b.Len() == 0) level.Set(slog.LevelDebug) l.Debug("detail") fmt.Println(b.Len() > 0)}LevelVar allows runtime filtering. Debug logging can increase cost and expose data; changes need controlled authorization and expiration. Sampling logs is separate from measuring all requests.
Expected output:
truetrueTry it locally
Create a derived logger with operation=lookup and log an error with code=unavailable; decode and print the two fields without timestamps.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reliability and observability 01: Design structured slog attributes and request IDs
Check the lesson objective before moving on.
Where should credentials appear in logs?
What does Logger.With return?