Subscribe

Structured logging in Go with log/slog

JSON logs from the Go standard library: log/slog handlers, a request ID added to every line through the context, log levels from config that change at runtime, and redacting passwords and tokens before they reach the log.

Structured logging in Go with log/slog

A log line like 2026/11/19 failed to create link for user 42: timeout is fine when you read it in a terminal. It's not fine when you want every failed request for user 42 in the last hour from CloudWatch or Loki. Structured logs write fields as key and value, usually JSON, so the log tool can filter on them. Go has had this in the standard library since 1.21, as log/slog. In this blog we will set up slog for a small HTTP service: a JSON handler, a request ID on every line, log levels from config, and redacting secrets.

Level is beginner. You should know how an http.Handler works (the REST API post covers it) and a bit about context from Tutorial 15. I used Go 1.27.3, no third party packages.

mkdir slogdemo && cd slogdemo
go mod init example.com/slogdemo
mkdir -p logging cmd/basics cmd/server

💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/Golang/structured-logging-in-go-with-log-slog. Clone it and run each step yourself.

The basics

package main

import (
    "log/slog"
    "os"
    "time"
)

func main() {
    // The default logger: text, Info and above.
    slog.Info("server starting", "port", 8080, "env", "dev")

    // A JSON logger.
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    logger.Info("link created", "code", "abc", "target", "https://example.com/x")
    logger.Debug("you will not see this, default level is Info")

    // Typed attributes avoid the odd-number-of-args mistake.
    logger.Warn("slow query",
        slog.String("query", "get_link"),
        slog.Duration("took", 1250*time.Millisecond),
        slog.Int("rows", 1),
    )

    // With adds fields to every line from this logger.
    reqLog := logger.With("request_id", "r-123", "user_id", 42)
    reqLog.Info("redirect", "code", "abc")

    // Groups nest fields.
    reqLog.Error("db call failed",
        slog.Group("db", slog.String("op", "insert"), slog.Int("attempt", 3)),
        "err", "connection reset",
    )
}
go run ./cmd/basics
2026/11/19 12:11:39 INFO server starting port=8080 env=dev
{"time":"2026-11-19T12:11:39.433042+05:30","level":"INFO","msg":"link created","code":"abc","target":"https://example.com/x"}
{"time":"2026-11-19T12:11:39.433049+05:30","level":"WARN","msg":"slow query","query":"get_link","took":1250000000,"rows":1}
{"time":"2026-11-19T12:11:39.433056+05:30","level":"INFO","msg":"redirect","request_id":"r-123","user_id":42,"code":"abc"}
{"time":"2026-11-19T12:11:39.43306+05:30","level":"ERROR","msg":"db call failed","request_id":"r-123","user_id":42,"db":{"op":"insert","attempt":3},"err":"connection reset"}

A logger is a front end, Logger, plus a Handler that decides the format and where it goes. The standard library gives you TextHandler (key=value) and JSONHandler. I'd use text on a laptop and JSON everywhere else.

Look at "took":1250000000. The JSON handler writes a time.Duration as nanoseconds. That actually surprised me the first time I ran it. Nobody wants to read that in a dashboard, so for anything a human reads I log milliseconds as an int, like duration_ms further down.

The odd number of arguments

logger.Info("msg", "key", value, ...) takes alternating keys and values. Leave a value out and slog doesn't fail, it writes this.

logger.Info("link created", "code")
{"time":"2026-11-19T12:12:17.786443+05:30","level":"INFO","msg":"link created","!BADKEY":"code"}

Good news, go vet catch it before you ship: call to slog.Logger.Info missing a final value. I put this line in my basics file first and go vet ./... failed on it straight away, so I moved it to its own folder. If your CI runs vet you're covered. The typed form, slog.String("code", c), can't have this problem at all.

A logging package

Now the setup for the service. One package that builds the logger from config, keeps the level adjustable, redacts secrets and pulls the request ID from the context.

// Package logging sets up slog for the service.
package logging

import (
    "context"
    "io"
    "log/slog"
    "strings"
)

// Level can be changed while the service runs.
var Level = new(slog.LevelVar)

var sensitive = map[string]bool{
    "password": true, "token": true, "authorization": true,
    "secret": true, "api_key": true, "cookie": true,
}

func redact(groups []string, a slog.Attr) slog.Attr {
    if sensitive[strings.ToLower(a.Key)] {
        return slog.String(a.Key, "[REDACTED]")
    }
    return a
}

// New builds the logger from config values (LOG_LEVEL, LOG_FORMAT).
func New(w io.Writer, level, format string) *slog.Logger {
    if err := Level.UnmarshalText([]byte(level)); err != nil {
        Level.Set(slog.LevelInfo)
    }
    opts := &slog.HandlerOptions{Level: Level, ReplaceAttr: redact}

    var h slog.Handler
    if format == "text" {
        h = slog.NewTextHandler(w, opts)
    } else {
        h = slog.NewJSONHandler(w, opts)
    }
    return slog.New(contextHandler{h})
}

// Secret is a string that never shows up in logs.
type Secret string

func (Secret) LogValue() slog.Value { return slog.StringValue("[REDACTED]") }

type ctxKey struct{}

// WithRequestID stores the request ID in the context.
func WithRequestID(ctx context.Context, id string) context.Context {
    return context.WithValue(ctx, ctxKey{}, id)
}

func RequestID(ctx context.Context) string {
    id, _ := ctx.Value(ctxKey{}).(string)
    return id
}

// contextHandler adds request_id from the context to every record.
type contextHandler struct{ slog.Handler }

func (h contextHandler) Handle(ctx context.Context, r slog.Record) error {
    if id := RequestID(ctx); id != "" {
        r.AddAttrs(slog.String("request_id", id))
    }
    return h.Handler.Handle(ctx, r)
}

func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
    return contextHandler{h.Handler.WithAttrs(attrs)}
}

func (h contextHandler) WithGroup(name string) slog.Handler {
    return contextHandler{h.Handler.WithGroup(name)}
}

There are three ideas in there.

First the level. slog.LevelVar is a level you can change while the program runs, safely from any goroutine. UnmarshalText parses debug, info, warn, error (any case), so LOG_LEVEL from the environment goes straight in. A bad value falls back to info. In a real service I'd rather fail at startup on a typo, but for a demo this much is fine.

Then redaction. ReplaceAttr runs on every attribute before it is written. Ours swaps the value of any key on the deny list. The Secret type is the other half: anything that implements LogValuer is asked for its log value, so a Secret prints [REDACTED] no matter what key you log it under. Use both. The key list catches the obvious password field, the type catches the API key someone logs as "key".

Last, the request ID. The wrapper handler reads the ID from the context and adds it to the record. Every call that uses the ...Context methods (InfoContext, ErrorContext) gets it for free. The shorty code that goes with the REST API post passes request_id by hand in its access log and error log. That works, but see, the next person who adds a log line will forget it. With this handler they can't.

If you wrap a handler, wrap WithAttrs and WithGroup too. If you don't, logger.With(...) returns the inner handler and your wrapper silently drops out.

Middleware and the server

The middleware takes the X-Request-Id header from the load balancer or makes a new ID, puts it on the response and into the context. The access log picks the level from the status code.

package main

import (
    "crypto/rand"
    "encoding/hex"
    "log/slog"
    "net/http"
    "os"
    "time"

    "example.com/slogdemo/logging"
)

type statusWriter struct {
    http.ResponseWriter
    status int
}

func (w *statusWriter) WriteHeader(code int) {
    w.status = code
    w.ResponseWriter.WriteHeader(code)
}

func requestIDs(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-Id")
        if id == "" {
            b := make([]byte, 8)
            rand.Read(b)
            id = hex.EncodeToString(b)
        }
        w.Header().Set("X-Request-Id", id)
        next.ServeHTTP(w, r.WithContext(logging.WithRequestID(r.Context(), id)))
    })
}

func accessLog(log *slog.Logger, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
        next.ServeHTTP(sw, r)

        level := slog.LevelInfo
        if sw.status >= 500 {
            level = slog.LevelError
        }
        log.LogAttrs(r.Context(), level, "request",
            slog.String("method", r.Method),
            slog.String("path", r.URL.Path),
            slog.Int("status", sw.status),
            slog.Int64("duration_ms", time.Since(start).Milliseconds()),
        )
    })
}

func main() {
    log := logging.New(os.Stdout, os.Getenv("LOG_LEVEL"), os.Getenv("LOG_FORMAT"))
    slog.SetDefault(log)

    links := map[string]string{"abc": "https://example.com/a/very/long/path"}

    mux := http.NewServeMux()
    mux.HandleFunc("GET /{code}", func(w http.ResponseWriter, r *http.Request) {
        code := r.PathValue("code")
        long, ok := links[code]
        if !ok {
            log.DebugContext(r.Context(), "code not found", "code", code)
            http.NotFound(w, r)
            return
        }
        http.Redirect(w, r, long, http.StatusFound)
    })
    mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) {
        r.ParseForm()
        log.InfoContext(r.Context(), "login attempt",
            "user", r.FormValue("user"),
            "password", r.FormValue("password"),
            "authorization", r.Header.Get("Authorization"),
        )
        w.WriteHeader(http.StatusNoContent)
    })
    // Change the level without a restart. Protect this in real life.
    mux.HandleFunc("PUT /admin/loglevel", func(w http.ResponseWriter, r *http.Request) {
        if err := logging.Level.UnmarshalText([]byte(r.URL.Query().Get("level"))); err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        log.WarnContext(r.Context(), "log level changed", "log_level", logging.Level.Level().String())
    })

    addr := os.Getenv("ADDR")
    if addr == "" {
        addr = ":8080"
    }
    log.Info("listening", "addr", addr, "log_level", logging.Level.Level().String())
    if err := http.ListenAndServe(addr, requestIDs(accessLog(log, mux))); err != nil {
        log.Error("server stopped", "err", err)
        os.Exit(1)
    }
}

LogAttrs with typed attributes is the fastest way to log in slog, it avoids boxing every value. Use it on the hot path, like the access log, and don't worry about it anywhere else.

The login handler is deliberately bad. It logs the password and the Authorization header, the kind of line someone adds while debugging and forgets. Let's see what comes out.

Running it

ADDR=127.0.0.1:18916 LOG_LEVEL=info go run ./cmd/server &

curl -s -o /dev/null -H 'X-Request-Id: demo-1' 127.0.0.1:18916/abc
curl -s -o /dev/null 127.0.0.1:18916/nope
curl -s -o /dev/null -H 'Authorization: Bearer eyJhbGciOi' \
  -d 'user=aravind&password=hunter2' 127.0.0.1:18916/login
curl -s -X PUT '127.0.0.1:18916/admin/loglevel?level=debug'
curl -s -o /dev/null 127.0.0.1:18916/nope2
curl -s -X PUT '127.0.0.1:18916/admin/loglevel?level=loud'

The last call answers slog: level string "loud": unknown name with a 400. Here is the log, trimmed to the interesting lines.

{"level":"INFO","msg":"request","method":"GET","path":"/abc","status":302,"duration_ms":0,"request_id":"demo-1"}
{"level":"INFO","msg":"request","method":"GET","path":"/nope","status":404,"duration_ms":0,"request_id":"474efa994d3e84ea"}
{"level":"INFO","msg":"login attempt","user":"aravind","password":"[REDACTED]","authorization":"[REDACTED]","request_id":"c254e60ee2e37370"}
{"level":"INFO","msg":"request","method":"POST","path":"/login","status":204,"duration_ms":0,"request_id":"c254e60ee2e37370"}
{"level":"WARN","msg":"log level changed","log_level":"DEBUG","request_id":"76ba23770b275dcb"}
{"level":"DEBUG","msg":"code not found","code":"nope2","request_id":"4d1c507764d2a741"}

The incoming demo-1 ID was kept, the others were generated. Password and token is gone. The first /nope had no debug line, /nope2 after the level change did. No restart.

Two things went wrong on my test runs, both worth knowing. My "listening" line used the key level for the configured level, and the text output came out as level=INFO msg=listening addr=... level=DEBUG. Two level key on one line. slog doesn't stop you reusing its own keys (time, level, msg, source), and a log tool will pick one of them. I renamed it to log_level. The second one: the "log level changed" line had no request ID, because I had written log.Warn instead of log.WarnContext. No context, no ID. A linter like sloglint can force the Context variants if your team keeps forgetting.

Testing the redaction

Redaction you don't test will break the day someone rename a field. This test writes to a buffer and checks that neither secret appears anywhere in the output.

func TestRedactAndRequestID(t *testing.T) {
    var buf bytes.Buffer
    log := New(&buf, "info", "json")

    ctx := WithRequestID(context.Background(), "r-1")
    log.InfoContext(ctx, "login", "user", "aravind", "password", "hunter2",
        "key", Secret("sk_live_123"))

    var line map[string]any
    if err := json.Unmarshal(buf.Bytes(), &line); err != nil {
        t.Fatal(err)
    }
    if line["password"] != "[REDACTED]" || line["key"] != "[REDACTED]" {
        t.Errorf("secret leaked: %s", buf.String())
    }
    if line["request_id"] != "r-1" {
        t.Errorf("request_id = %v", line["request_id"])
    }
    if strings.Contains(buf.String(), "hunter2") || strings.Contains(buf.String(), "sk_live") {
        t.Errorf("secret value found in output: %s", buf.String())
    }
}

It passes with go test -race ./..., together with a second test that checks the level change. A key list is only a safety net though. user_password or pwd sail straight through it. The real fix is not logging request bodies and headers in the first place, and the zap linting post shows a way to fail the build when someone tries.

A few more things

Since Go 1.26 there's slog.NewMultiHandler, which sends each record to several handlers. That's handy for text on stderr while you develop plus JSON to a file. Before that you needed a small custom handler or a third party one.

If you are using zap or zerolog since a long time, there's no rush to move. But a library you publish should take a *slog.Logger, so callers can plug in whatever they use. Once the logs are JSON, CloudWatch Logs Insights can filter on request_id or status directly, which is the whole point of this exercise.

My last tip: log the request ID back to the user in error responses too. When someone sends you a screenshot of an error page, that one string finds every line of that request.