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.
On this page
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.
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)
}
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=3The 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:
package main
import "log/slog"
func main() {
slog.Warn("row skipped", "line", 5, "reason")
}
main.go:6:2: call to slog.Warn missing a final value2026/12/03 18:36:27 WARN row skipped line=5 !BADKEY=reasonThe 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.
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")
}
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.
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)
}
{"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.
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
<?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.LoggerwithWithfields instead of a global. - Run
go vetto catch a missing key or value.
Tomorrow: generics, to write a function once for many types.