Groups

April 28, 2026

Early bird registration for [**Idiomatic Testing in Go**](/idiomatic-testing/) ends today!

Not sure how to adapt your xUnit habits to Go? This is the course for you!

Sign up today to save 25% over the full price.

Sometimes you want to group several key/value attributes together when logging. Maybe different aspects of an error (error_code, error_detail, stacktrace, etc), or different aspects of an HTTP response (bytes_sent, status_code, etc). The log/slog package gives us this!

Groups

Attributes can be collected into groups. A group has a name that is used to qualify the names of its attributes. How this qualification is displayed depends on the handler. TextHandler separates the group and attribute names with a dot. JSONHandler treats each group as a separate JSON object, with the group name as the key.

Use Group to create a Group attribute from a name and a list of key-value pairs:

slog.Group("request",
    "method", r.Method,
    "url", r.URL)

TextHandler would display this group as

request.method=GET request.url=http://example.com

JSONHandler would display it as

"request":{"method":"GET","url":"http://example.com"}

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Values

TIL Logger.LogAttrs is a thing! But what is that thing?? Yesterday I mentioned that using an slog.Attr can be marginally more efficient than using naked key/value pairs in a log call. While true, that glosses over what is likely to be a much more impactful performance consideration in certain applications… Attrs and Values … The value part of an Attr is a type called Value. Like an [any], a Value can hold any Go value, but it can represent typical values, including all numbers and strings, without an allocation.


Attrs

We’ve been talking about key/value pairs. The log/slog package has a name for these: Attr (short for “attribute”). And there’s more than one way to build an attribute: Attrs and Values An Attr is a key-value pair. The Logger output methods accept Attrs as well as alternating keys and values. The statement slog.Info("hello", slog.Int("count", 3)) behaves the same as slog.Info("hello", "count", 3) There are convenience constructors for Attr such as Int, String, and Bool for common types, as well as the function Any for constructing Attrs of any type.


Contexts

[**Idiomatic Testing in Go**](/idiomatic-testing/) starts TOMORROW! My my, how time flies! There are still a few seats available, and there’s still time to sign up. Learn how to get the most out of the tests in your Go app! One feature I often see overlooked capability of the log/slog package, is to extract log key/value pairs from context: Contexts Some handlers may wish to include information from the context.Context that is available at the call site.

Get daily content like this in your inbox!

Subscribe