Back to Concepts Roadmap
🔥 Level 12 — Architecture & Practices
Architecture

Structured Logging with log/slog

Production logging with standard structured key-value attributes in Go 1.21+.

Real-World Analogy (Mental Model)

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`.
Step-by-Step Code

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.

example.goGo 1.24+
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("User logged in", slog.String("userId", "usr_123"), slog.Int("attempts", 1))
Battle-Tested Production Case Study

How Uber Built Zap: Zero-Allocation High-Speed Structured Logging

Uber Architecture
Production Challenge

Traditional reflection-based logging (e.g. `log.Printf("%v", data)`) caused millions of interface boxing heap allocations, saturating the CPU with GC tracking.

Architectural Solution

Designed Zap around strongly-typed field encoders (`zap.String()`, `zap.Int()`) that write bytes directly into pre-allocated memory buffers without interface boxing.

production_pattern.goLogging became 10x faster than standard library loggers with 0 heap allocations in the critical path.
// 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

Mistake: Misusing structured logging with log/slog without understanding its memory or concurrency semantics.
✅ Correct Way: Always follow standard Go idioms and verify with tests.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

What is the primary concept behind Structured Logging with log/slog?

Finished this lesson?

Mark it as complete to track your overall Go mastery.