Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 147 ยท Standard Library

Logging with log and slog

Learn logging in Go with the log package and structured log/slog - levels, attributes, groups, text and JSON handlers, ReplaceAttr, custom handlers, LogValuer and logging best practices.

When a program runs on a server you can't attach a debugger, and nobody is sitting at a terminal. Logs are how you learn what happened: which request failed, which user triggered it, how long a job took. Go has two logging packages in the standard library: the classic log, which writes simple lines of text, and log/slog (added in Go 1.21), which writes structured records with a level and key-value attributes that tools can search and filter.

You'll start with log because it's everywhere in existing code, then spend most of the lesson on slog, which is what new programs should use.

The log package

log.Println and log.Printf write a line to standard error, prefixed by the date and time. A *log.Logger lets you pick the destination, a prefix and which extra information to show:

Go log.Logger, prefixes and flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The flags are bits you combine with |: log.Ldate, log.Ltime, log.Lmicroseconds, log.LUTC, log.Lshortfile, log.Llongfile and log.Lmsgprefix (put the prefix right before the message). The default is Ldate | Ltime.

Fatal and Panic

Two families of functions do more than print:

  • log.Fatal, Fatalf, Fatalln print and then call os.Exit(1). Deferred functions do not run.
  • log.Panic, Panicf, Panicln print and then call panic, so deferred functions do run and recover is possible.

Use Fatal only in main, for errors that make continuing pointless (a missing config file). In libraries, return an error instead, as described in Errors as Values.

The log package has no levels, no fields and no JSON. You can fake levels with prefixes, but for anything beyond a script, move to slog.

Structured logging with slog

A structured log record has a time, a level, a message and any number of attributes (key-value pairs). Instead of building sentences by hand ("user 42 failed login from 10.0.0.1"), you log a fixed message and put the variable parts in attributes. Log aggregation tools can then answer "show me every record with user_id=42" without parsing text.

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

Go Text handler with levels and attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The four standard levels are slog.LevelDebug (-4), LevelInfo (0), LevelWarn (4) and LevelError (8). A logger discards records below its minimum level, which by default is Info: so the Debug call above only shows because we lowered the level in HandlerOptions. Levels are plain integers, which means you can define your own, and the gaps are there for that purpose.

Attributes, more safely

Alternating "key", value arguments are convenient, but a missing value or a non-string key becomes a !BADKEY entry at run time, which go vet can detect. The type-safe alternative is slog.Attr values such as slog.String, slog.Int, slog.Bool, slog.Duration, slog.Time and slog.Any, passed with LogAttrs:

Go Attr values and LogAttrs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

LogAttrs is also the fastest way to log, because it avoids converting arguments to an Attr at run time. The last line shows what a missing value looks like: !BADKEY=key.

JSON output and groups

Production systems usually want JSON, one object per line. The JSON handler has the same options; only the format changes. Groups nest attributes under a prefix: slog.Group("request", ...) produces a nested object in JSON and dotted keys (request.method) in text.

Go JSON handler and groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Loggers with context: With

In real programs you want some attributes on every record of a request or component: a request ID, a user, a service name. logger.With(...) returns a new logger that includes those attributes, so you create it once and pass it around (or store it in a struct):

Go With adds permanent attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

With evaluates its arguments once, so handlers can pre-format them, which also makes this faster than repeating the attributes in every call.

The default logger

slog.Info(...) and friends use the default logger. slog.SetDefault(logger) replaces it, and it also redirects the old log package, so libraries that still call log.Println end up in your structured output. Out of the box the default logger writes through log, so records look like 2025/01/02 15:04:05 INFO message key=value on standard error.

Hiding secrets with LogValuer

A type can control how it appears in logs by implementing slog.LogValuer. Use it to redact passwords, tokens and personal data once, instead of remembering at every call site:

Go LogValuer redacts a password

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Changing the level while running

Pass a *slog.LevelVar as the handler's Level and change it at any time, safely from several goroutines. A common use is an admin endpoint or a signal that switches to Debug for a few minutes:

Go LevelVar and a custom handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A slog.Handler has four methods: Enabled (cheap check before any work), Handle (format and write one record), WithAttrs and WithGroup (return a derived handler). Most programs never write one; the built-in text and JSON handlers, or a third-party one for a specific backend, are enough. This example skips group support to stay short.

Logging best practices

  • Log events, not sentences. Keep the message constant ("payment failed") and put variable data in attributes.
  • Log or return an error, not both. If you log an error and also return it, every layer logs it again. Handle it once, at the place that decides what to do (Error Handling Patterns explains this).
  • Choose levels honestly. Debug for developers, Info for normal milestones, Warn for odd but recoverable, Error for failed operations that need attention.
  • Be consistent with key names (user_id, not userID in one place and uid in another).
  • Never log secrets or personal data. Redact them with LogValuer.
  • Write to stdout or stderr and let the platform ship logs, instead of managing files in the program.
  • Pass loggers explicitly (as a field or parameter) in libraries; avoid hidden globals that make tests hard.
  • Use *Context variants (InfoContext) when a handler extracts a request ID from the context.

Output from a logger that includes timestamps is different on every run, which breaks tests that compare text. In tests, use a ReplaceAttr function like the one above to remove the time, or write to a bytes.Buffer and check substrings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between log.Fatal and log.Panic?

    Fatal calls os.Exit(1). Panic calls panic, which unwinds the stack and runs deferred functions.
  2. 2. With the default settings, is slog.Debug("x") printed?

    The default level is Info (0), so Debug (-4) records are dropped unless you lower the level in HandlerOptions.
  3. 3. What does logger.Info("hi", "user") log for the attribute?

    An odd number of arguments leaves a key without a value; slog reports it as !BADKEY instead of failing. go vet warns about it.
  4. 4. What is logger.With("request_id", id) for?

    With does not modify the original; it derives a logger with attributes attached.
  5. 5. Why implement slog.LogValuer on a User type?

    LogValue returns the value to log, so secrets such as passwords can be left out everywhere the type is logged.

Summary

  • log writes plain lines (to stderr by default); log.New gives a logger with its own destination, prefix and flags. Fatal exits without running defers; Panic panics.
  • log/slog produces structured records: time, level, message and key-value attributes.
  • Levels are Debug (-4), Info (0), Warn (4), Error (8); the default minimum is Info, adjustable with HandlerOptions.Level or a LevelVar.
  • NewTextHandler and NewJSONHandler choose the output format; ReplaceAttr renames, redacts or removes attributes (for example the time).
  • slog.Group, WithGroup and With nest and attach attributes; LogAttrs with typed Attr values is type-safe and fast.
  • slog.SetDefault also routes the old log package through your handler.
  • Log events with constant messages, log or return an error (not both), and never log secrets.

Next: Command-Line Programs: flag and os.Args shows how to make your programs configurable.