log/slog

A log line is data: a level, a message and a set of key and value pairs. log/slog writes that shape, and a handler decides whether it becomes text for a person or JSON for a collector. The package replaced the formatted lines of log for new code in Go 1.21, and it is the logger the HTTP service in the next part uses.

slog.Info and a text handler

A logger is a handler plus a level. The text handler writes level=, msg= and then the pairs, quoting a value that contains a space. The timestamp is part of every line by default; the ReplaceAttr below drops it, which makes the output of this lesson stable enough to show.

package main import ( "log/slog" "os" ) func main() { opts := &slog.HandlerOptions{ Level: slog.LevelDebug, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return slog.Attr{} } return a }, } logger := slog.New(slog.NewTextHandler(os.Stdout, opts)) logger.Info("started", "port", 8080) logger.Debug("detail", "count", 3) }

go build -o app main.go && ./app

level=INFO msg=started port=8080
level=DEBUG msg=detail count=3

The pairs are untyped, so "port", 8080 is an int and prints without quotes, while a string with a space would be quoted. The typed helpers slog.Int and slog.String say the same thing and cost no reflection, which matters in a hot path.

Levels

The handler level is the minimum it writes: a handler at Info drops Debug and passes Info, Warn and Error. The level can come from a flag or an environment variable, and a program that sets it once at start-up turns its own verbosity down in production without a rebuild.

package main import ( "log/slog" "os" ) func main() { opts := &slog.HandlerOptions{ Level: slog.LevelInfo, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return slog.Attr{} } return a }, } logger := slog.New(slog.NewTextHandler(os.Stdout, opts)) logger.Debug("hidden") logger.Info("visible") logger.Warn("careful", "disk", "90%") }

go build -o app main.go && ./app

level=INFO msg=visible
level=WARN msg=careful disk=90%

The debug line produced nothing, which is the point: the message is still in the binary and costs an argument check when the level is off. A level of slog.LevelDebug shows it, and a custom level can sit between the four built-ins.

A JSON handler

The JSON handler writes one object per line with the same keys, which a log collector parses without a regular expression. With returns a logger that carries the pairs on every line, so a request id is attached once and appears in the message, the warning and the error that follow.

package main import ( "log/slog" "os" ) func main() { opts := &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 := slog.New(slog.NewJSONHandler(os.Stdout, opts)) logger.With("request_id", "req-42").Info("handled", slog.String("method", "GET"), slog.Int("status", 200), ) }

go build -o app main.go && ./app

{"level":"INFO","msg":"handled","request_id":"req-42","method":"GET","status":200}

The id precedes the pairs of the message, and the status is a number rather than a string. A collector that indexes status can filter on it, which is the difference between a log a machine reads and a sentence a machine has to guess at.

An error as an attribute

An error value in a pair is written as its message, quoted when it has spaces. The handler does not unwrap it or add a stack; a program that wants the chain logs slog.Any("error", err) and accepts the text, and a program that needs the type logs a separate kind field.

package main import ( "errors" "log/slog" "os" ) func main() { opts := &slog.HandlerOptions{ Level: slog.LevelDebug, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return slog.Attr{} } return a }, } logger := slog.New(slog.NewTextHandler(os.Stdout, opts)) err := errors.New("connection refused") logger.Error("request failed", "error", err, "retry", false) }

go build -o app main.go && ./app

level=ERROR msg="request failed" error="connection refused" retry=false

The message has a space and is quoted; the error is quoted for the same reason. A handler that wants the error to be machine-readable writes JSON and gets "error":"connection refused"; the level and the message are the two fields every collector understands.

Structured logging

Four habits make a log useful six months later. Log at the boundary of a request, with the id and the outcome. Put the data in pairs instead of the message, so it can be filtered. Never log a password, a token or a whole request body. And keep one logger per program, passed to the code that needs it or read from slog.Default, rather than a different format per package.

The handler is also the seam for tests: slog.NewTextHandler(&buf, nil) collects the lines in a buffer, and a test asserts on the pair it cares about without parsing stdout. The next part starts the HTTP server, and its middleware is a natural place for the request line this lesson formats.

Exercises

  1. Log a value with a space in it and a value with a quote. Which one is quoted, and how is the quote written?
  2. Set the level to slog.LevelWarn and run the first program. Which lines survive, and what does that say about where a debug line belongs?
  3. Write a test that logs into a bytes.Buffer and checks the request_id pair. What does the buffer hold, and why is that easier than capturing stdout?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a slog record?

    Answer

    A level, a message and key and value pairs

    The handler decides the rendering.

  2. What does the handler level do?

    Answer

    Drops records below it

    A debug line costs almost nothing when off.

  3. What does a JSON handler write?

    Answer

    One JSON object per line

    A collector parses one line at a time.

  4. What does logger.With do?

    Answer

    Returns a logger that adds the pairs to every record

    A request id is attached once.

  5. How is an error value logged?

    Answer

    As its message in the pair

    A handler formats the text it is given.

  6. Why does the lesson drop the time attribute?

    Answer

    To make the shown output stable

    A real program keeps the timestamp.

  7. Which helper logs an int without reflection?

    Answer

    slog.Int

    The typed helpers avoid the any conversion.

  8. Why put data in pairs instead of the message?

    Answer

    A collector can filter and index it

    The message is for a person.

  9. What must never be logged?

    Answer

    Passwords, tokens and whole request bodies

    A log is copied to many places.

  10. How does a test capture slog output?

    Answer

    A handler writing to a bytes.Buffer

    The handler is the seam.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev