Go 1.21 added log/slog to the standard library — a structured logger with handlers for text and JSON, contextual attributes via context, and a stable interface that third-party libraries are converging on. The era of every Go service picking between logrus and zap is over for new code. This article shows the slog layout Stack Harbor uses on Go services we run.
How to verify
A minimal slog program emits JSON to stdout:
cat > /tmp/slog-demo.go <<'EOF'
package main
import (
"log/slog"
"os"
)
func main() {
h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
slog.SetDefault(slog.New(h))
slog.Info("hello", "service", "demo", "version", "1.0.0")
}
EOF
go run /tmp/slog-demo.go | jq
You should see {"time":"...","level":"INFO","msg":"hello","service":"demo","version":"1.0.0"}. That’s the format every container log collector (Loki, Fluent Bit, Vector) understands without parsing rules.
What’s happening
log/slog has three pieces:
slog.Logger— the front-end you call (logger.Info,logger.Error).slog.Handler— the back-end that formats and writes (JSON, text, or custom).slog.Record— the structured event flowing between them, with key/value attributes.
A Logger forwards records to its handler. The standard library ships TextHandler (human-readable kv pairs) and JSONHandler (one JSON object per line). You can write your own handler for non-stdlib formats — for example, a handler that injects OpenTelemetry trace IDs.
The contextual logging pattern uses slog.LoggerFromContext or a helper to derive a logger with request-scoped attributes (request ID, user ID, tenant). The derived logger forwards to the same handler but carries the extra attributes — so every log line in a request automatically has the correlation fields.
slog deliberately doesn’t have Fatal or Panic. The standard library treats those as application concerns: log first, then call os.Exit(1) or panic yourself. Resist the temptation to wrap them.
The procedure
-
Bootstrap slog as the default logger. In
main.go:package main import ( "log/slog" "os" ) func main() { level := new(slog.LevelVar) level.Set(slog.LevelInfo) h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: level, AddSource: true, }) logger := slog.New(h).With( "service", "billing", "version", buildVersion, "env", os.Getenv("APP_ENV"), ) slog.SetDefault(logger) // Now anywhere in your code: slog.Info("...") }AddSource: trueaddssource.functionandsource.file:lineto each record — useful in dev, optional in prod for cost reasons. -
Make the level dynamic. A
LevelVaryou can flip without restart:level := new(slog.LevelVar) http.HandleFunc("/admin/log-level", func(w http.ResponseWriter, r *http.Request) { v := r.URL.Query().Get("level") switch v { case "debug": level.Set(slog.LevelDebug) case "info": level.Set(slog.LevelInfo) case "warn": level.Set(slog.LevelWarn) case "error": level.Set(slog.LevelError) } w.WriteHeader(204) })Gate that endpoint behind your admin auth.
-
Per-request contextual attributes. A middleware that derives a request-scoped logger:
type loggerKey struct{} func logMW(base *slog.Logger) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqID := r.Header.Get("X-Request-ID") if reqID == "" { reqID = uuid.NewString() } l := base.With( "request_id", reqID, "method", r.Method, "path", r.URL.Path, ) ctx := context.WithValue(r.Context(), loggerKey{}, l) next.ServeHTTP(w, r.WithContext(ctx)) }) } } func loggerFromCtx(ctx context.Context) *slog.Logger { if l, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok { return l } return slog.Default() }Handlers call
log := loggerFromCtx(r.Context())and every log line automatically carries the request ID. -
Group nested attributes. Use
slog.Groupto organize:slog.Info("charge completed", slog.Group("customer", "id", customerID, "tier", tier, ), slog.Group("payment", "amount", amount, "currency", currency, "method", method, ), )The JSON output is nested:
{"customer": {"id": "...", "tier": "..."}, ...}. -
Custom handler that injects OTel trace IDs. Common need on observed services:
type otelHandler struct{ slog.Handler } func (h otelHandler) Handle(ctx context.Context, r slog.Record) error { sc := trace.SpanContextFromContext(ctx) if sc.IsValid() { r.AddAttrs( slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()), ) } return h.Handler.Handle(ctx, r) } // Wire it: base := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}) slog.SetDefault(slog.New(otelHandler{Handler: base})) -
Error logging with structured attrs. Avoid
Sprintfin messages — keep the message constant and the data structured:if err := chargeCustomer(ctx, id); err != nil { slog.ErrorContext(ctx, "charge failed", "customer_id", id, "err", err, ) return err }slog.ErrorContext(notError) passes the context to the handler — required for the OTel handler above to find the trace. -
Quiet third-party packages. Bind their loggers to a discardd handler or a slog-backed shim:
silent := slog.NewTextHandler(io.Discard, nil) thirdparty.SetLogger(slog.New(silent))
Common pitfalls
slog.Info("...", "k1", v1, "k2")(odd number of args) silently logs!BADKEY. Useslog.Attrhelpers (slog.String("k", v),slog.Int("n", n)) when you want compile-time safety.- Logging a pointer to a struct logs the address. Implement
LogValue() slog.Valueon the type or pass fields explicitly. - The default logger is the global
slog.Default(). Replacing it mid-process is racy under load. Set it once inmainbefore the server starts. AddSource: trueadds ~30% overhead on hot paths. Off in production unless debugging.- Levels are integers.
LevelDebug = -4,LevelInfo = 0,LevelWarn = 4,LevelError = 8. Custom levels work but most JSON consumers prefer the standard names — setHandlerOptions.ReplaceAttrto map ints to strings if needed.
Stack Harbor uses slog as the default logger on every new Go service we ship, with the OTel-aware handler and dynamic level flipping baked in. See how that fits into our managed operations practice when log volume and correlation become operations problems.