Logging in Go

Logging means writing down what your program is doing while it runs, so you can find out later what went wrong. Go ships two logging packages: log for simple messages and log/slog for structured logs with levels. This lesson covers both, starting simple, and shows you when to use which.

Why not fmt.Println?

You could print messages with fmt.Println, and for a quick debug session that’s fine. For anything that runs longer, a logger gives you three things fmt doesn’t: a timestamp on every line, output to standard error instead of standard output, and (with slog) levels and machine-readable fields.

The log package

The log package works like fmt, with Println, Printf and Print:

package main

import "log"

func main() {
	log.Println("starting up")
	log.Printf("loaded %d items", 42)
}Code language: Go (go)
2026/11/08 21:40:08 starting up
2026/11/08 21:40:08 loaded 42 itemsCode language: plaintext (plaintext)

Each line gets the date and time in front (yours will show the current time), and a newline at the end if you didn’t add one.

Logs go to stderr

A program has two output streams. Standard output (stdout) is for the program’s actual results; standard error (stderr) is for messages about how it’s going. Both show up in your terminal, but they can be redirected separately. log writes to stderr, so your log lines don’t end up mixed into the results:

package main

import (
	"fmt"
	"log"
)

func main() {
	fmt.Println("result: 42")
	log.Println("computed the result")
}Code language: Go (go)

Build it and send stdout to a file with >. Only the log line still appears in the terminal, and the file contains only the result:

go build -o prog .
./prog > out.txt
cat out.txtCode language: Bash (bash)
2026/11/08 21:37:47 computed the result
result: 42Code language: plaintext (plaintext)

The first line came from ./prog (stderr, straight to the terminal), the second from cat out.txt.

Flags and prefixes

log.SetFlags controls what goes in front of each message. log.Lshortfile adds the file name and line number, which is great for finding where a message came from. 0 removes everything. log.SetPrefix adds your own text:

package main

import "log"

func main() {
	log.SetFlags(log.Lshortfile)
	log.Println("where am I?")

	log.SetFlags(0)
	log.SetPrefix("myapp: ")
	log.Println("no timestamp, but a prefix")
}Code language: Go (go)
main.go:7: where am I?
myapp: no timestamp, but a prefixCode language: plaintext (plaintext)

If you need more than one logger, log.New(os.Stdout, "prefix: ", log.LstdFlags) creates one with its own output, prefix and flags.

log.Fatal stops the program

log.Fatal (and log.Fatalf) logs the message and then exits the program with status 1. It’s handy at the start of main, when something your program can’t work without is missing:

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	defer fmt.Println("this never prints")

	log.SetFlags(0)
	_, err := os.Open("missing.txt")
	if err != nil {
		log.Fatal(err)
	}
}Code language: Go (go)
open missing.txt: no such file or directoryCode language: plaintext (plaintext)

(With go run you’ll also see exit status 1; that line comes from the go tool, not from your program.)

log.Fatal exits immediately: deferred functions don’t run, as the example shows. Files may not get flushed and connections don’t get closed. Use it only in main, never in a package other code imports. Everywhere else, return an error and let the caller decide.

Where log falls short

The log package is fine for small tools. In a service that runs for weeks, you quickly want more:

  • Levels. Debug detail while developing, only warnings and errors in production.
  • Structure. A line like user 42 logged in from 10.0.0.1 is easy to read but hard to search. Log tools want fields: user=42 ip=10.0.0.1, or JSON.

For years that meant a third-party library. Since Go 1.21, the standard library has log/slog (structured logging), and it’s what I use in new code.

Structured logging with log/slog

With slog, every log call takes a message followed by key-value pairs:

package main

import "log/slog"

func main() {
	slog.Info("user logged in", "user", 42, "ip", "10.0.0.1")
	slog.Warn("disk almost full", "free_gb", 2)
}Code language: Go (go)
2026/11/08 21:40:09 INFO user logged in user=42 ip=10.0.0.1
2026/11/08 21:40:09 WARN disk almost full free_gb=2Code language: plaintext (plaintext)

The message stays constant ("user logged in"), and the details that change go in fields. That’s what makes structured logs searchable: you can find every user logged in line, or every line with user=42.

The top-level functions use the default logger, which writes through the log package (hence the same timestamp format, on stderr). To choose the format yourself, create a logger with a handler.

Handlers: text or JSON

A *slog.Logger is what your code calls. A slog.Handler decides what happens to each record: which levels to keep, how to format it, and where to write it. The standard library comes with two handlers:

A slog Logger hands records to a Handler Your code calls a method on a slog.Logger with a message and key-value pairs. The Logger passes the record to its Handler, which filters by level and writes it out. A TextHandler writes key=value text, a JSONHandler writes one JSON object per line. Your logging calls stay the same when you swap the handler. your code logger.Info( “started”, “port”, 8080) handler checks the level, formats the record, writes it out TextHandler level=INFO msg=started port=8080 JSONHandler {“level”:”INFO”, “msg”:”started”,…} or
Your code talks to the Logger; the Handler decides the format. Swap the handler and every log line changes, without touching the calls.

slog.NewTextHandler writes key=value pairs, easy for people to read:

package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
	logger.Info("started", "port", 8080)
}Code language: Go (go)
time=2026-11-08T21:40:09.789+01:00 level=INFO msg=started port=8080Code language: plaintext (plaintext)

slog.NewJSONHandler writes one JSON object per line, which log collectors and cloud logging services can parse without any setup:

package main

import (
	"log/slog"
	"os"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
	logger.Info("started", "port", 8080)
}Code language: Go (go)
{"time":"2026-11-08T21:40:10.193632+01:00","level":"INFO","msg":"started","port":8080}Code language: plaintext (plaintext)

The logging call is identical; only the handler changed. I use the text handler while developing and JSON in production. The first argument is an io.Writer, so the logs can go to os.Stderr, os.Stdout or a file. The second is a *slog.HandlerOptions; nil means the defaults.

Removing the time (or changing any field)

The ReplaceAttr option is a function that sees every field before it’s written, and can change or drop it. Returning an empty slog.Attr{} drops the field. I’ll use it to remove the time, which keeps the output in the rest of this lesson the same every time you run it. (In real programs keep the time; you’ll want it.)

package main

import (
	"log/slog"
	"os"
)

func dropTime(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: dropTime}
	logger := slog.New(slog.NewTextHandler(os.Stdout, opts))
	logger.Info("started", "port", 8080)
}Code language: Go (go)
level=INFO msg=started port=8080Code language: plaintext (plaintext)

The len(groups) == 0 check makes sure only the top-level time is dropped, not a field you happened to call time inside a group (more on groups below).

Levels

slog has four levels, from least to most severe: Debug, Info, Warn and Error. Each has a method on the logger. By default, handlers drop everything below Info. Set the Level option to change that:

package main

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

func dropTime(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: dropTime}
	logger := slog.New(slog.NewTextHandler(os.Stdout, opts))

	logger.Debug("cache lookup", "key", "user:42")
	logger.Info("request handled", "status", 200)
	logger.Warn("slow request", "ms", 1250)
	logger.Error("save failed", "err", errors.New("disk full"))

	opts.Level = slog.LevelDebug
	verbose := slog.New(slog.NewTextHandler(os.Stdout, opts))
	verbose.Debug("cache lookup", "key", "user:42")
}Code language: Go (go)
level=INFO msg="request handled" status=200
level=WARN msg="slow request" ms=1250
level=ERROR msg="save failed" err="disk full"
level=DEBUG msg="cache lookup" key=user:42Code language: plaintext (plaintext)

The first Debug call printed nothing. With Level: slog.LevelDebug, the second one did. Notice the text handler adds quotes around values that contain spaces, so the output stays parseable. For errors, the convention is the key "err" with the error as the value.

To change the level while the program runs (say, from a command-line flag or an admin endpoint), use a slog.LevelVar as the Level option and call its Set method later.

Attributes and With

The alternating "key", value arguments are short, but easy to get wrong: forget a key and the pairs shift. The typed helpers slog.String, slog.Int, slog.Bool, slog.Any and friends make each field explicit. You can mix both styles.

When several lines share fields, logger.With returns a new logger that adds them to every line. I use it to tag everything that happens during one request or one job:

package main

import (
	"log/slog"
	"os"
)

func dropTime(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: dropTime}
	logger := slog.New(slog.NewTextHandler(os.Stdout, opts))

	logger.Info("order placed", slog.Int("order", 1001), slog.String("currency", "EUR"))

	jobLog := logger.With("job", "nightly-report", "run", 7)
	jobLog.Info("job started")
	jobLog.Info("job finished", slog.Int("rows", 1520))
}Code language: Go (go)
level=INFO msg="order placed" order=1001 currency=EUR
level=INFO msg="job started" job=nightly-report run=7
level=INFO msg="job finished" job=nightly-report run=7 rows=1520Code language: plaintext (plaintext)

go vet knows about slog. If you pass a key without a value, like logger.Info("msg", "user"), it reports call to slog.Logger.Info missing a final value before your program even runs.

Groups

Groups put related fields under a common name. slog.Group groups some fields in one call; logger.WithGroup puts all later fields of a logger in a group. The text handler joins the names with a dot, the JSON handler nests objects:

package main

import (
	"log/slog"
	"os"
)

func dropTime(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: dropTime}
	text := slog.New(slog.NewTextHandler(os.Stdout, opts))
	json := slog.New(slog.NewJSONHandler(os.Stdout, opts))

	req := slog.Group("request", "method", "GET", "path", "/orders")
	text.Info("handled", req, "status", 200)
	json.Info("handled", req, "status", 200)
}Code language: Go (go)
level=INFO msg=handled request.method=GET request.path=/orders status=200
{"level":"INFO","msg":"handled","request":{"method":"GET","path":"/orders"},"status":200}Code language: plaintext (plaintext)

slog.SetDefault

Passing a logger to every function is the cleanest design, but for most programs it’s enough to configure one logger at the start of main and make it the default with slog.SetDefault. After that, the top-level slog.Info and friends use it, and so does the old log package:

package main

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

func dropTime(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: dropTime}
	slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, opts)))

	slog.Info("config loaded", "path", "/etc/app.toml")
	log.Println("a message from older code")
}Code language: Go (go)
{"level":"INFO","msg":"config loaded","path":"/etc/app.toml"}
{"level":"INFO","msg":"a message from older code"}Code language: plaintext (plaintext)

That second line matters in practice: dependencies that still use log.Println end up in the same JSON stream as the rest of your logs.

Writing your own handler

slog.Handler is an interface with four methods (Enabled, Handle, WithAttrs and WithGroup). Any type that implements it can be plugged into slog.New: to send logs to a service, color them in the terminal, or add fields to every record. Most programs never need one. If yours does, start with the Handler documentation and the slog introduction on the Go blog.

What about Zap, Logrus and friends?

Before slog, structured logging in Go meant a third-party library, and you’ll still find Zap, zerolog and Logrus in many existing projects. They’re well made, and there’s no need to rip them out of a project that works. For new code, I start with slog: it’s in the standard library, every Go developer can read it, and in most programs logging speed isn’t the bottleneck. Because the handler is an interface, switching later doesn’t mean rewriting your log calls: you keep the slog calls and put a different handler behind them.

Practice

1. A request logger. Create a JSON logger on stdout without the time field. Make a child logger with With that adds "request_id", "abc123", then log an Info line "fetching user" with "user", 42 and an Error line "user not found" with an "err" field.

Show a solution
package main

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

func dropTime(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: dropTime}
	logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))

	reqLog := logger.With("request_id", "abc123")
	reqLog.Info("fetching user", "user", 42)
	reqLog.Error("user not found", "err", errors.New("no rows"))
}Code language: Go (go)
{"level":"INFO","msg":"fetching user","request_id":"abc123","user":42}
{"level":"ERROR","msg":"user not found","request_id":"abc123","err":"no rows"}Code language: plaintext (plaintext)

2. A debug switch. Write a program with a verbose boolean variable. If it’s true, the text logger should show Debug messages; otherwise only Info and above. Log one Debug and one Info message, and run it with verbose set to true.

Show a solution
package main

import (
	"log/slog"
	"os"
)

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

func main() {
	verbose := true

	level := slog.LevelInfo
	if verbose {
		level = slog.LevelDebug
	}
	opts := &slog.HandlerOptions{Level: level, ReplaceAttr: dropTime}
	logger := slog.New(slog.NewTextHandler(os.Stdout, opts))

	logger.Debug("parsed flags", "verbose", verbose)
	logger.Info("ready")
}Code language: Go (go)
level=DEBUG msg="parsed flags" verbose=true
level=INFO msg=readyCode language: plaintext (plaintext)

Set verbose := false and only the ready line remains. In a real program the value would come from a command-line flag.

Key takeaways

  • The log package writes timestamped lines to stderr. SetFlags and SetPrefix change the format.
  • log.Fatal exits with status 1 without running deferred functions. Only use it in main.
  • log/slog logs a constant message plus key-value fields, with levels Debug, Info, Warn and Error.
  • The handler sets the format: NewTextHandler for people, NewJSONHandler for machines. HandlerOptions sets the level and can rewrite fields.
  • Use With for shared fields, groups for related ones, and slog.SetDefault to route all logging (even log.Println) through one handler.