Go core
Browse topics

Structured logging with log/slog

Version
1.27
Since
1.21
Review
Draft

Summary#

log/slog records a message, a level and key-value attributes. A handler chooses the output format. With returns a logger that adds the same attributes to every record.

Syntax#

go
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger = logger.With("service", "billing")
logger.Info("invoice created", "id", 42)

Example#

go
package main

import (
	"log/slog"
	"os"
)

func main() {
	options := &slog.HandlerOptions{
		Level: slog.LevelInfo,
		ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
			if len(groups) == 0 && attr.Key == slog.TimeKey {
				return slog.Attr{} // drop the timestamp
			}
			return attr
		},
	}

	text := slog.New(slog.NewTextHandler(os.Stdout, options)).With("service", "billing")
	text.Debug("hidden below the minimum level")
	text.Info("invoice created", "id", 42)

	structured := slog.New(slog.NewJSONHandler(os.Stdout, options))
	structured.Warn("retrying", slog.Int("attempt", 2))
}

Expected output#

Text
level=INFO msg="invoice created" service=billing id=42
{"level":"WARN","msg":"retrying","attempt":2}

Common mistakes#

Pass attributes as complete key-value pairs or as slog.Attr values. A key without a value is recorded under !BADKEY. Run go vet, whose slog check reports malformed argument lists.

Version applicability#

log/slog was added in Go 1.21. Earlier programs use the log package or a third-party structured logger. The slog vet check arrived in Go 1.22.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0