Structured Logging With slog

Emit structured logs with the standard slog package so records carry typed key-value attributes that are easy to filter and correlate.

GoResilience

Code

gosnippet
24 lines
package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo,
	}))

	logger.Info("request handled",
		slog.String("method", "GET"),
		slog.String("path", "/users/42"),
		slog.Int("status", 200),
		slog.Duration("latency", 0),
	)

	logger.Error("dependency failed",
		slog.String("dependency", "postgres"),
		slog.Int("attempt", 3),
	)
}

How it works

Count the function main as the entire surface area of Structured Logging With slog.

main builds a logger with slog.NewJSONHandler(os.Stdout, ...) at slog.LevelInfo, so every record is one JSON object on stdout. logger.Info("request handled", ...) attaches typed attributes — method GET, path /users/42, status 200, and a zero-value slog.Duration named latency. logger.Error("dependency failed", ...) records dependency postgres with attempt 3. Because the attributes are typed key-value pairs inside the JSON record rather than interpolated message text, log filters can query status or dependency directly.

Interactive Tools for This Topic

FAQ

How do you run Structured Logging With slog?
It runs as-is — treat the file as the whole program and execute it.