Go

log/slog — Structured Logging

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`log/slog` (Go 1.21+) is the standard structured logger. Drop-in replacement for `log` with key/value attributes and JSON output for log-pipeline ingestion.
Go
Raw
package main

import (
    "log/slog"
    "os"
)

func main() {
    // Text handler for humans
    text := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug})
    logger := slog.New(text)
    logger.Info("user signed in", "user_id", 42, "ip", "10.0.0.1")
    logger.Warn("retrying", "attempt", 3, "max", 5)

    // JSON handler for machines (ELK, Loki, Datadog, etc.)
    j := slog.NewJSONHandler(os.Stdout, nil)
    jl := slog.New(j)
    jl.Info("event", "kind", "purchase", "amount_cents", 999)
    // {"time":"...","level":"INFO","msg":"event","kind":"purchase","amount_cents":999}

    // Common attributes attached to every log line
    requestLogger := slog.Default().With("request_id", "req-abc")
    requestLogger.Info("handling")
    requestLogger.Error("failed", "err", "timeout")

    // Make this the default logger app-wide:
    slog.SetDefault(slog.New(j))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.