Go Playbook

Course › Week 3 · Real data and speed › Day 3 · lesson 17 of 42 · 10 min reading + 45 min practice

Structured logging with slog

Log lines with fields, as text or JSON, on stderr, at the level you choose.

log/sloglevelsJSON logsstderr

On this page
  1. Fields, not formatted strings
  2. Handlers
  3. Levels and shared fields
  4. Where logs go
  5. Coming from PHP
  6. Practice
  7. Remember

A log line like import failed for 9002 after 3 tries is easy to read and hard to search. A structured log line keeps the values as fields: msg="import failed" evaluation_id=9002 attempts=3. A person still reads it; a log collector can filter on evaluation_id.

Go’s standard library has that built in since Go 1.21: log/slog. Today: logging with fields, text and JSON output, levels, fields on every line, and where logs go.

Fields, not formatted strings

1. slog.Info with key-value pairs

Each logging function takes a message, then pairs of key and value. The message is a constant; everything that changes is a field.

main.go
package main

import "log/slog"

func main() {
	slog.Info("import started", "file", "responses.csv")
	slog.Warn("row skipped", "line", 5, "reason", "score is not a number")
	slog.Info("import finished", "rows", 4, "skipped", 3)
}
$ go run .
2026/12/03 18:36:27 INFO import started file=responses.csv
2026/12/03 18:36:27 WARN row skipped line=5 reason="score is not a number"
2026/12/03 18:36:27 INFO import finished rows=4 skipped=3

The default logger writes to stderr, with the date and time, the level and the message, then the fields as key=value. Keep messages as fixed text ("row skipped", never "row 5 skipped"), so you can search for every line of one kind.

2. A missing value

The pairs are just arguments, so the compiler cannot check them. go vet can:

main.go
package main

import "log/slog"

func main() {
	slog.Warn("row skipped", "line", 5, "reason")
}
go vet ./...
main.go:6:2: call to slog.Warn missing a final value
$ go run .
2026/12/03 18:36:27 WARN row skipped line=5 !BADKEY=reason

The program runs, and the log line gets a !BADKEY, which is how slog marks a value with no key. The vet check is the reason to run go vet ./... before every commit, not only staticcheck.

Handlers

3. A text handler

slog.New(handler) makes a logger; the handler decides the format and where it goes. slog.NewTextHandler(os.Stderr, nil) writes every line as key=value pairs, including the time and the level.

main.go
package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))

	logger.Info("import started", "file", "responses.csv")
	logger.Warn("row skipped", "line", 5, "reason", "score is not a number")
}
$ go run .
time=2026-12-03T18:36:28.356+02:00 level=INFO msg="import started" file=responses.csv
time=2026-12-03T18:36:28.356+02:00 level=WARN msg="row skipped" line=5 reason="score is not a number"

Values with spaces are quoted. nil means the default options; section 5 sets some.

4. A JSON handler

slog.NewJSONHandler writes one JSON object per line, for log collectors such as CloudWatch, Datadog or Loki.

main.go
package main

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

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stderr, nil))

	err := errors.New("connection refused")
	logger.Error("import failed", "file", "responses.csv", "attempts", 3, "err", err)
}
$ go run .
{"time":"2026-12-03T18:36:29.042983792+02:00","level":"ERROR","msg":"import failed","file":"responses.csv","attempts":3,"err":"connection refused"}

An error as a value is written as its message. "err" is the usual key for it. The calling code does not change at all between text and JSON: only the handler does, so the tool can pick the format from a flag.

Levels and shared fields

5. The level, from the environment

By default Debug lines are dropped. slog.HandlerOptions{Level: …} sets the lowest level a handler writes. slog.Level can parse its own name, so the level can come from an environment variable, like LOG_LEVEL in a Laravel .env.

main.go
package main

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

func main() {
	level := slog.LevelInfo
	if name := os.Getenv("LOG_LEVEL"); name != "" {
		if err := level.UnmarshalText([]byte(name)); err != nil {
			fmt.Fprintln(os.Stderr, "LOG_LEVEL:", err)
			os.Exit(2)
		}
	}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level}))

	logger.Debug("reading row", "line", 2)
	logger.Info("import finished", "rows", 4)
}
$ go run .
time=2026-12-03T18:36:29.770+02:00 level=DEBUG msg="reading row" line=2
time=2026-12-03T18:36:29.770+02:00 level=INFO msg="import finished" rows=4

os.Getenv returns the variable, or "" when it is not set. UnmarshalText takes bytes, hence []byte(name), and accepts debug, info, warn and error in any case. A bad value is a usage error, exit code 2, before anything is logged.

Run with LOG_LEVEL=debug go run ., as here, and the debug line appears. Without it, only import finished is written.

6. With: fields on every line

logger.With(key, value, …) returns a logger that adds those fields to every line. Make one per job, request or file, and pass it down.

main.go
package main

import (
	"log/slog"
	"os"
)

func importFile(logger *slog.Logger, path string) {
	logger = logger.With("file", path)

	logger.Info("import started")
	logger.Warn("row skipped", "line", 5)
	logger.Info("import finished", "rows", 4)
}

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stderr, nil)).With("run", "nightly")

	importFile(logger, "responses-a.csv")
	importFile(logger, "responses-b.csv")
}
$ go run .
time=2026-12-03T18:36:30.388+02:00 level=INFO msg="import started" run=nightly file=responses-a.csv
time=2026-12-03T18:36:30.389+02:00 level=WARN msg="row skipped" run=nightly file=responses-a.csv line=5
time=2026-12-03T18:36:30.389+02:00 level=INFO msg="import finished" run=nightly file=responses-a.csv rows=4
time=2026-12-03T18:36:30.389+02:00 level=INFO msg="import started" run=nightly file=responses-b.csv
time=2026-12-03T18:36:30.389+02:00 level=WARN msg="row skipped" run=nightly file=responses-b.csv line=5
time=2026-12-03T18:36:30.389+02:00 level=INFO msg="import finished" run=nightly file=responses-b.csv rows=4

*slog.Logger is the type to pass. importFile does not need to know about run, and the caller does not need to know about file; every line carries both. It is Laravel’s Log::withContext(), without anything global.

Passing the logger as a parameter is the usual Go way. slog.SetDefault(logger) also exists, to make it the logger behind slog.Info; use it in main at most, never in a package.

Where logs go

7. stdout is for data, stderr is for logs

A tool like the build day’s csv2json writes its result to stdout, so it can be piped: csv2json responses.csv > responses.jsonl. Every log line goes to stderr, so it never ends up inside the JSON file, and a script can read the two separately.

That is why every handler on this page writes to os.Stderr. Laravel apps log to files because PHP serves web requests; a Go service or tool logs to stderr and lets the system around it (systemd, Docker, Kubernetes) collect it.

Coming from PHP

ImportResponses.php
<?php
Log::withContext(['run' => 'nightly']);

Log::info('import started', ['file' => $path]);
Log::warning('row skipped', ['line' => 5, 'reason' => 'score is not a number']);

Laravel’s logger is Monolog, and the context array is exactly slog’s fields. The differences: slog’s fields are arguments, so go vet can check them, and a logger with fields is a value you pass, not global state that the next request might inherit.

Monolog’s channels and handlers map to slog’s handlers. There is no built-in daily file in slog, on purpose: write to stderr and let the platform rotate.

PracticeThe slog guide, and a log format flag

Read the first half of the Go blog post Structured Logging with slog, from the Go team.

Exercise: -log-format

Take the program of section 5 and add a -log-format flag with the values text (the default) and json. Any other value is a usage error with exit code 2. Build the handler in one function, newLogger(format string, level slog.Level) (*slog.Logger, error), and give it a table test that checks the error for an unknown format.

Remember

  • A log message is fixed text; everything that changes is a key-value field.
  • Logs go to stderr, data to stdout; pass a *slog.Logger with With fields instead of a global.
  • Run go vet to catch a missing key or value.

Tomorrow: generics, to write a function once for many types.