Skip to content

Go Log Slog Structured

DodaTech 1 min read

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.
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

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead 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

**How to set log level in slog?**

Use slog.HandlerOptions{Level: slog.LevelDebug}.

What attributes does slog support?

String, Int, Int64, Uint64, Float64, Bool, Time, Duration, Group, Any.

Can I use slog with external services?

Yes. Implement slog.Handler interface for custom backends.


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