Structured logging with log/slog

suggest change

The log package writes lines of free-form text. That's fine for a small tool, but in a server you want to search and filter logs: "all errors for user 42", "requests slower than 1 second". That needs structured logs, where every record is a message plus key-value attributes that a machine can parse.

Package log/slog was added to the standard library in Go 1.21. It does what used to require third-party libraries like zap or zerolog. This article covers:

All examples were run with Go 1.27. When an API is newer than Go 1.21, the text says which version added it.

The basics

The package-level functions slog.Debug, slog.Info, slog.Warn and slog.Error log a message followed by alternating keys and values:

package main

import (
	"log"
	"log/slog"
	"time"
)

func main() {
	slog.Info("server starting", "port", 8080, "tls", false)
	slog.Warn("slow request", "path", "/api/users", "took", 1200*time.Millisecond)
	slog.Error("query failed", "err", "connection refused", "attempt", 3)
	slog.Debug("not shown: default level is Info")

	// the old log package and slog share the same output
	log.Printf("plain log message")
}
2026/10/17 23:31:52 INFO server starting port=8080 tls=false
2026/10/17 23:31:52 WARN slow request path=/api/users took=1.2s
2026/10/17 23:31:52 ERROR query failed err="connection refused" attempt=3
2026/10/17 23:31:52 plain log message

The default logger writes through the log package, so the output looks like log output with a level and key=value pairs added. Values with spaces are quoted and a time.Duration prints as 1.2s.

Debug messages are dropped because the default minimum level is Info.

The levels are just integers: LevelDebug is -4, LevelInfo is 0, LevelWarn is 4 and LevelError is 8. The gaps leave room for your own levels, shown later.

Text and JSON handlers

A *slog.Logger is a thin front end. The work of formatting and writing a record is done by a slog.Handler. The standard library has two:

package main

import (
	"log/slog"
	"os"
)

func main() {
	text := slog.New(slog.NewTextHandler(os.Stdout, nil))
	text.Info("user logged in", "user", "ann", "id", 42, "admin", true)
	text.Info("quoted values", "note", "has spaces", "empty", "")

	json := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	json.Info("user logged in", "user", "ann", "id", 42, "admin", true)
}
time=2026-10-17T23:31:53.162+02:00 level=INFO msg="user logged in" user=ann id=42 admin=true
time=2026-10-17T23:31:53.164+02:00 level=INFO msg="quoted values" note="has spaces" empty=""
{"time":"2026-10-17T23:31:53.1641295+02:00","level":"INFO","msg":"user logged in","user":"ann","id":42,"admin":true}

Every record has the built-in attributes time, level and msg, followed by yours.

A common setup is text output in development and JSON in production, picked by a flag or an environment variable. Since both are slog.Handler, the rest of the code doesn't change.

Most of the remaining examples remove the time attribute so that the output is the same on every run. How that's done is explained in the ReplaceAttr section below.

Key-value pairs vs slog.Attr

There are two ways to pass attributes. Alternating keys and values is short. A slog.Attr, created with slog.String, slog.Int, slog.Int64, slog.Bool, slog.Float64, slog.Duration, slog.Time or slog.Any, is typed:

package main

import (
	"context"
	"errors"
	"log/slog"
	"os"
	"time"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{} // drop time for reproducible output
			}
			return a
		},
	}))

	// key-value pairs: short to write
	logger.Info("download", "file", "a.zip", "bytes", 1048576)

	// typed Attrs: checked by the compiler, fewer allocations
	logger.Info("download",
		slog.String("file", "a.zip"),
		slog.Int64("bytes", 1048576),
		slog.Duration("took", 1500*time.Millisecond),
		slog.Time("at", time.Date(2026, 10, 17, 9, 30, 0, 0, time.UTC)),
		slog.Any("err", errors.New("disk full")),
	)

	// LogAttrs accepts only Attrs: the fastest form
	logger.LogAttrs(context.Background(), slog.LevelInfo, "download",
		slog.String("file", "b.zip"), slog.Bool("cached", true))

	// mistakes: a missing value and a non-string key
	logger.Info("oops", "file")
	logger.Info("oops", 42, "x")
}
{"level":"INFO","msg":"download","file":"a.zip","bytes":1048576}
{"level":"INFO","msg":"download","file":"a.zip","bytes":1048576,"took":1500000000,"at":"2026-10-17T09:30:00Z","err":"disk full"}
{"level":"INFO","msg":"download","file":"b.zip","cached":true}
{"level":"INFO","msg":"oops","!BADKEY":"file"}
{"level":"INFO","msg":"oops","!BADKEY":42,"!BADKEY":"x"}

Things to notice:

go vet catches these mistakes at build time:

$ go vet .
.\main.go:38:2: call to slog.Logger.Info missing a final value
.\main.go:39:22: slog.Logger.Info arg "42" should be a string or a slog.Attr (possible missing key or value)

In practice key-value pairs are fine for most code, especially since go vet (and so go test) checks them. Use slog.Attr and LogAttrs in hot paths.

Adding common attributes with With

Logger.With returns a new logger that adds the given attributes to every record. Use it for attributes that are the same for a whole component or request, so you don't repeat them in every call:

package main

import (
	"log/slog"
	"os"
)

func handle(logger *slog.Logger, path string) {
	logger = logger.With("path", path)
	logger.Info("request started")
	logger.Info("request finished", "status", 200)
}

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}))
	logger = logger.With("service", "api", "version", "1.4.2")

	handle(logger.With("request_id", "r-1"), "/users")
	handle(logger.With("request_id", "r-2"), "/orders")
}
level=INFO msg="request started" service=api version=1.4.2 request_id=r-1 path=/users
level=INFO msg="request finished" service=api version=1.4.2 request_id=r-1 path=/users status=200
level=INFO msg="request started" service=api version=1.4.2 request_id=r-2 path=/orders
level=INFO msg="request finished" service=api version=1.4.2 request_id=r-2 path=/orders status=200

With doesn't modify the original logger. Handlers format the attributes passed to With once, when the new logger is created, not on every log call, so a logger with many common attributes is cheap to use.

Passing a *slog.Logger to functions (or storing it in a struct) is the usual way to give code a logger that carries its context. See Dependency injection.

HandlerOptions: level, source and ReplaceAttr

The second argument of NewTextHandler and NewJSONHandler is *slog.HandlerOptions:

package main

import (
	"log/slog"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	opts := &slog.HandlerOptions{
		Level:     slog.LevelDebug, // log Debug and above
		AddSource: true,            // add file:line of the call
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if len(groups) > 0 {
				return a // only touch top-level attributes
			}
			switch a.Key {
			case slog.TimeKey:
				return slog.Attr{} // drop time
			case slog.LevelKey:
				// "INFO" => "info"
				return slog.String("severity", strings.ToLower(a.Value.String()))
			case slog.MessageKey:
				a.Key = "message"
			case slog.SourceKey:
				// full path => file name only
				src := a.Value.Any().(*slog.Source)
				src.File = filepath.Base(src.File)
			case "password":
				return slog.String("password", "***")
			}
			return a
		},
	}
	logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
	logger.Debug("connecting", "host", "db.local", "password", "hunter2")
	logger.Info("connected")
}
{"severity":"debug","source":{"function":"main.main","file":"main.go","line":37},"message":"connecting","host":"db.local","password":"***"}
{"severity":"info","source":{"function":"main.main","file":"main.go","line":38},"message":"connected"}

The keys of the built-in attributes are the constants slog.TimeKey, slog.LevelKey, slog.MessageKey and slog.SourceKey. ReplaceAttr is also called for attributes inside groups; the groups argument lists the groups the attribute is in, so check len(groups) == 0 before treating "time" as the built-in time.

AddSource has a cost: getting the caller's location takes a call to runtime.Callers on every record.

Masking a key in ReplaceAttr works as a safety net, but it's better to make sensitive types redact themselves. See Keeping secrets out of code and logs for a Secret type that implements LogValue.

Changing the level at runtime with LevelVar

HandlerOptions.Level is a slog.Leveler, an interface with a single Level() method. A slog.Level constant is fixed. A *slog.LevelVar can be changed later, safely from any goroutine, and the handler sees the new level immediately:

package main

import (
	"context"
	"log/slog"
	"os"
)

const LevelTrace = slog.Level(-8)

func main() {
	ctx := context.Background()
	var level slog.LevelVar // zero value is LevelInfo
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		Level: &level,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			if a.Key == slog.LevelKey && a.Value.Any().(slog.Level) == LevelTrace {
				a.Value = slog.StringValue("TRACE")
			}
			return a
		},
	}))

	logger.Debug("debug 1: hidden")
	logger.Info("info 1")

	level.Set(slog.LevelDebug) // e.g. on SIGUSR1 or from an admin endpoint
	logger.Debug("debug 2: now visible")

	level.Set(LevelTrace)
	logger.Log(ctx, LevelTrace, "very detailed")
	logger.Log(ctx, slog.LevelInfo+2, "between info and warn")

	// levels can be parsed from config or environment
	var fromEnv slog.Level
	if err := fromEnv.UnmarshalText([]byte("warn")); err == nil {
		level.Set(fromEnv)
	}
	logger.Info("info 2: hidden")
	logger.Warn("warn", "level", level.Level())
}
level=INFO msg="info 1"
level=DEBUG msg="debug 2: now visible"
level=TRACE msg="very detailed"
level=INFO+2 msg="between info and warn"
level=WARN msg=warn level=WARN

This lets you turn on debug logging in a running server, e.g. from an admin HTTP endpoint or a signal handler, without a restart.

Custom levels are any slog.Level value. Without help they print relative to the nearest standard level below them (INFO+2, DEBUG-4), so name them in ReplaceAttr.

Level.UnmarshalText parses names like "debug", "WARN" or "info+2", which is handy for reading the level from a config file or an environment variable.

Groups and GroupAttrs

A group puts related attributes under one key. The text handler joins the names with a dot; the JSON handler creates a nested object:

package main

import (
	"log/slog"
	"os"
)

func noTime(groups []string, a slog.Attr) slog.Attr {
	if a.Key == slog.TimeKey && len(groups) == 0 {
		return slog.Attr{}
	}
	return a
}

func main() {
	opts := &slog.HandlerOptions{ReplaceAttr: noTime}
	text := slog.New(slog.NewTextHandler(os.Stdout, opts))
	json := slog.New(slog.NewJSONHandler(os.Stdout, opts))

	// slog.Group takes key-value pairs or Attrs
	req := slog.Group("req", "method", "GET", "path", "/users")
	// slog.GroupAttrs (Go 1.25) takes only Attrs
	user := slog.GroupAttrs("user", slog.Int("id", 42), slog.String("name", "ann"))

	text.Info("handled", req, user, "status", 200)
	json.Info("handled", req, user, "status", 200)

	// WithGroup puts all later attributes into a group
	db := json.WithGroup("db").With("host", "db.local")
	db.Info("query", "rows", 3, slog.Group("timing", "ms", 12))

	// an empty group is omitted
	text.Info("empty", slog.Group("nothing"))
}
level=INFO msg=handled req.method=GET req.path=/users user.id=42 user.name=ann status=200
{"level":"INFO","msg":"handled","req":{"method":"GET","path":"/users"},"user":{"id":42,"name":"ann"},"status":200}
{"level":"INFO","msg":"query","db":{"host":"db.local","rows":3,"timing":{"ms":12}}}
level=INFO msg=empty

LogValuer: controlling how a type is logged

If a type implements slog.LogValuer, its LogValue() slog.Value method decides how it is logged. Use it to log only some fields of a struct, or to return a group:

package main

import (
	"fmt"
	"log/slog"
	"os"
)

type User struct {
	ID    int
	Name  string
	Email string
	Roles []string
}

// LogValue controls how a User appears in logs
func (u User) LogValue() slog.Value {
	return slog.GroupValue(
		slog.Int("id", u.ID),
		slog.String("name", u.Name),
	)
}

// expensive is computed only if the record is actually logged
type expensive struct{ n int }

func (e expensive) LogValue() slog.Value {
	fmt.Println("  (computing expensive value)")
	return slog.IntValue(e.n * e.n)
}

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}))
	u := User{ID: 42, Name: "ann", Email: "ann@example.com", Roles: []string{"admin"}}
	logger.Info("login", "user", u)

	logger.Debug("stats", "sq", expensive{12}) // Debug is disabled: not computed
	logger.Info("stats", "sq", expensive{12})
}
level=INFO msg=login user.id=42 user.name=ann
  (computing expensive value)
level=INFO msg=stats sq=144

Email and Roles never reach the log, no matter how many places log a User.

LogValue is called only when a record is actually written. In the example the value isn't computed for the disabled Debug call. That makes LogValuer a way to make expensive values lazy.

For hiding secrets with LogValue, see Keeping secrets out of code and logs.

SetDefault and the log package

slog.SetDefault replaces the logger used by slog.Info and friends. It also redirects the log package, so log.Printf calls in your code and in libraries end up in the same handler:

package main

import (
	"log"
	"log/slog"
	"os"
)

func main() {
	// 1. The default slog logger writes through the log package
	slog.Info("before SetDefault", "n", 1)

	// 2. After SetDefault, log.Printf goes through the slog handler too
	h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	})
	slog.SetDefault(slog.New(h))
	slog.Info("after SetDefault", "n", 2)
	log.Printf("from log.Printf: %d", 3)

	// Go 1.22: choose the level of messages coming from the log package
	slog.SetLogLoggerLevel(slog.LevelWarn)
	log.Printf("legacy warning")

	// 3. A *log.Logger for APIs that need one, e.g. http.Server.ErrorLog
	errLog := slog.NewLogLogger(h, slog.LevelError)
	errLog.Println("http: TLS handshake error")
}
{"level":"INFO","msg":"after SetDefault","n":2}
{"level":"INFO","msg":"from log.Printf: 3"}
{"level":"WARN","msg":"legacy warning"}
{"level":"ERROR","msg":"http: TLS handshake error"}
2026/10/17 23:31:59 INFO before SetDefault n=1

Call SetDefault once, at the start of main.

Context-aware logging

Every logging method has a Context variant: DebugContext, InfoContext, WarnContext, ErrorContext, and Log and LogAttrs take a context as the first argument. The logger doesn't do anything with the context; it passes it to the handler.

The built-in handlers ignore it, but a handler that wraps another one can take values from the context, like a request ID or a trace ID set by middleware:

package main

import (
	"context"
	"log/slog"
	"os"
)

type ctxKey struct{}

func WithRequestID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, ctxKey{}, id)
}

// ContextHandler adds request_id from the context to every record
type ContextHandler struct {
	slog.Handler
}

func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error {
	if id, ok := ctx.Value(ctxKey{}).(string); ok {
		r.AddAttrs(slog.String("request_id", id))
	}
	return h.Handler.Handle(ctx, r)
}

func (h ContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	return ContextHandler{h.Handler.WithAttrs(attrs)}
}

func (h ContextHandler) WithGroup(name string) slog.Handler {
	return ContextHandler{h.Handler.WithGroup(name)}
}

func loadUser(ctx context.Context, id int) {
	slog.InfoContext(ctx, "loading user", "id", id)
}

func main() {
	base := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	})
	slog.SetDefault(slog.New(ContextHandler{base}))

	ctx := WithRequestID(context.Background(), "r-7f3a")
	loadUser(ctx, 42)
	slog.With("component", "cache").InfoContext(ctx, "miss")
	slog.Info("no context, no request_id")
}
level=INFO msg="loading user" id=42 request_id=r-7f3a
level=INFO msg=miss component=cache request_id=r-7f3a
level=INFO msg="no context, no request_id"

Embedding slog.Handler in the struct gives ContextHandler the wrapped handler's Enabled, so only Handle, WithAttrs and WithGroup are needed. The last two must return a wrapped handler, otherwise loggers created with With would lose the context handling.

One detail: Handle adds request_id to the record, so after WithGroup("x") it would appear as x.request_id. If that matters, write a full handler like the next one.

See context.WithValue for how to store values in a context.

Writing a custom Handler

A slog.Handler has four methods:

Here's a compact console handler that prints LEVEL file:line message key=value:

package main

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"os"
	"path/filepath"
	"strings"
	"sync"
)

// ConsoleHandler writes: LEVEL file:line message key=value ...
type ConsoleHandler struct {
	mu     *sync.Mutex // shared by all handlers derived from this one
	w      io.Writer
	level  slog.Leveler
	attrs  string // pre-formatted attributes from WithAttrs
	prefix string // group prefix from WithGroup, e.g. "db."
}

func NewConsoleHandler(w io.Writer, level slog.Leveler) *ConsoleHandler {
	return &ConsoleHandler{mu: &sync.Mutex{}, w: w, level: level}
}

func (h *ConsoleHandler) Enabled(_ context.Context, l slog.Level) bool {
	return l >= h.level.Level()
}

func (h *ConsoleHandler) Handle(_ context.Context, r slog.Record) error {
	var b strings.Builder
	fmt.Fprintf(&b, "%-5s ", r.Level)
	if src := r.Source(); src != nil { // Record.Source: Go 1.25
		fmt.Fprintf(&b, "%s:%d ", filepath.Base(src.File), src.Line)
	}
	b.WriteString(r.Message)
	b.WriteString(h.attrs)
	r.Attrs(func(a slog.Attr) bool {
		appendAttr(&b, h.prefix, a)
		return true // keep going
	})
	b.WriteByte('\n')

	h.mu.Lock()
	defer h.mu.Unlock()
	_, err := io.WriteString(h.w, b.String())
	return err
}

func appendAttr(b *strings.Builder, prefix string, a slog.Attr) {
	a.Value = a.Value.Resolve() // call LogValue if needed
	if a.Equal(slog.Attr{}) {
		return // ignore empty attributes
	}
	if a.Value.Kind() == slog.KindGroup {
		if a.Key != "" {
			prefix += a.Key + "."
		}
		for _, ga := range a.Value.Group() {
			appendAttr(b, prefix, ga)
		}
		return
	}
	fmt.Fprintf(b, " %s%s=%v", prefix, a.Key, a.Value)
}

func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	h2 := *h // copy, never modify h
	var b strings.Builder
	for _, a := range attrs {
		appendAttr(&b, h.prefix, a)
	}
	h2.attrs += b.String()
	return &h2
}

func (h *ConsoleHandler) WithGroup(name string) slog.Handler {
	if name == "" {
		return h
	}
	h2 := *h
	h2.prefix += name + "."
	return &h2
}

func main() {
	logger := slog.New(NewConsoleHandler(os.Stdout, slog.LevelDebug))
	logger.Debug("starting", "pid", 1234)
	db := logger.With("component", "db").WithGroup("db")
	db.Info("connected", "host", "db.local", slog.Group("pool", "size", 10))
	logger.Error("failed", "err", fmt.Errorf("timeout after %ds", 5))
}
DEBUG main.go:89 starting pid=1234
INFO  main.go:91 connected component=db db.host=db.local db.pool.size=10
ERROR main.go:92 failed err=timeout after 5s

The rules that a handler must follow:

Record.Source, added in Go 1.25, returns a *slog.Source with the function, file and line of the log call, or nil if the record has no program counter. Before Go 1.25 you had to call runtime.CallersFrames on Record.PC yourself.

Record.Attrs iterates over the record's attributes without allocating a slice. Use Record.NumAttrs if you need the count.

Package testing/slogtest runs a set of checks against a handler; use it to test a handler meant for general use.

Multiple destinations with NewMultiHandler

slog.NewMultiHandler, added in Go 1.26, sends each record to several handlers. Each one keeps its own level and format, so you can show readable Info logs on the console and write detailed JSON logs to a file:

package main

import (
	"fmt"
	"log/slog"
	"os"
)

func noTime(groups []string, a slog.Attr) slog.Attr {
	if a.Key == slog.TimeKey && len(groups) == 0 {
		return slog.Attr{}
	}
	return a
}

func main() {
	f, err := os.Create("app.log")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// human-readable Info+ on stdout, JSON Debug+ in a file
	console := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo, ReplaceAttr: noTime,
	})
	file := slog.NewJSONHandler(f, &slog.HandlerOptions{
		Level: slog.LevelDebug, ReplaceAttr: noTime,
	})
	logger := slog.New(slog.NewMultiHandler(console, file)) // Go 1.26

	logger = logger.With("app", "shop")
	logger.Debug("cache warmed", "items", 120)
	logger.Info("listening", "addr", ":8443")

	data, _ := os.ReadFile("app.log")
	fmt.Print("--- app.log ---\n", string(data))
}
level=INFO msg=listening app=shop addr=:8443
--- app.log ---
{"level":"DEBUG","msg":"cache warmed","app":"shop","items":120}
{"level":"INFO","msg":"listening","app":"shop","addr":":8443"}

The multi handler is enabled for a level if any of its handlers is, and calls Handle only on the handlers that are enabled for the record. Attributes from With and WithGroup are passed to all of them. If several handlers return errors, Handle returns them joined with errors.Join.

Performance and testing tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents