Go Log Slog Structured
In this tutorial, you'll learn about Go slog: Structured Logging. We cover key concepts, practical examples, and best practices.
slog structured logging -- Use Go 1.21's log/slog package with structured attributes for better observability.
The Problem
slog defaults to text format. Use slog.JSONHandler for structured output. Attach contextual attributes using slog.With.
Wrong
slog.Info("user login", "user", name, "ip", ip)
Output:
// Key-value pairs, but default is text format.
Right
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("user login",
slog.String("user", name),
slog.String("ip", ip),
slog.Int("attempts", attempts))
Output:
{"time":"2026-06-24T10:00:00Z","level":"INFO","msg":"user login","user":"alice","ip":"10.0.0.1","attempts":3}
Prevention
- Use slog.NewJSONHandler for JSON structured output
- Use slog.NewTextHandler for human-readable
- Use typed attributes: slog.String, slog.Int, slog.Bool
- Use slog.Group for nested fields
- slog is part of Go standard library (Go 1.21+)
Common Mistakes with log slog structured
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro