Go by Example

Logging

Use log/slog handlers and structured fields; configure JSON or text output, levels, and sensitive-data handling.

log/slog is Go's built-in package for structured logs. A structured log stores details such as a message and level, its importance such as information or error, as separate fields so another tool can search them.

Choose JSON, a text format for named data fields, when the tool that collects your logs expects it. Add details as key-value pairs. A child logger can add the same detail, such as a request ID, to every message it writes.

package main
 
import (
    "log/slog"
    "os"
)
 
func main() {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    logger.With("request_id", "abc-123").
        Info("request complete", "status", 200)
}

In production

Choose the output format and minimum level to match the system that reads the logs. Add an identifier for the current web request when one is available, but never log passwords or access tokens. Set HandlerOptions.Level to hide lower-priority messages such as debug details. The default handler writes readable text to standard error.

Enjoyed this? Get more software craft delivered to your inbox.