Structured Logging with log/slog
Production logging with standard structured key-value attributes in Go 1.21+.
“A flight black box recorder: saving logs in structured JSON format with timestamps and tags so search engines can index them instantly.”
Key Concepts & Rules To Remember
- Standard library `log/slog` replaces third-party loggers.
- Outputs structured JSON or high-performance text.
- Supports strongly-typed attributes like `slog.String` and `slog.Int`.
1. Understanding Structured Logging with log/slog
Production logging with standard structured key-value attributes in Go 1.21+. In Go, structured logging with log/slog is designed around clarity and high runtime efficiency.
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("User logged in", slog.String("userId", "usr_123"), slog.Int("attempts", 1))How Uber Built Zap: Zero-Allocation High-Speed Structured Logging
Traditional reflection-based logging (e.g. `log.Printf("%v", data)`) caused millions of interface boxing heap allocations, saturating the CPU with GC tracking.
Designed Zap around strongly-typed field encoders (`zap.String()`, `zap.Int()`) that write bytes directly into pre-allocated memory buffers without interface boxing.
// Zero-allocation structured field logging:
logger.Info("failed to fetch user",
zap.String("user_id", "usr_99"),
zap.Int("attempt", 3),
zap.Duration("backoff", time.Second),
)Common Beginner Pitfalls & Mistakes
Knowledge Check
Verify your understanding with these interactive practice questions.
Quizzes
Quick checks for understanding
Multiple-choice with inline explanations—expand to see why.
Finished this lesson?
Mark it as complete to track your overall Go mastery.