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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.