Slog WithGroup Nests Attributes

WithGroup prefixes attributes added after it under a dotted path, while With pins attributes onto every later record from that logger scope.

GoConfig Management

Code

gosnippet
31 lines
package main

import (
	"log/slog"
	"os"
)

func main() {
	// drop the time attribute so repeated runs print identical lines
	handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return a
		},
	})
	base := slog.New(handler)

	// With attaches attributes that appear on every record from this logger
	scoped := base.With("request_id", "r-1042")
	scoped.Info("payment accepted", "amount_cents", 4950)

	// WithGroup nests every later attribute under a dotted prefix
	httpLog := scoped.WithGroup("http")
	httpLog.Info("route matched", "method", "GET", "path", "/orders")

	// nested groups compose into deeper dotted paths
	dbLog := httpLog.WithGroup("db")
	dbLog.Warn("slow query", "ms", 412)
}

How it works

Slog WithGroup Nests Attributes reduces to the function main.

Caveats

  • It carries its own context — no imports beyond the runtime’s own surface.

Using it

Signature: func main()

The key statements that remain

return slog.Attr{}

Interactive Tools for This Topic

FAQ

How do you run Slog WithGroup Nests Attributes?
Run the file on its own; every call resolves against the standard surface it already imports.