log/slog: add GroupAttrs

GroupAttrs is a more efficient version of Group
that takes a slice of Attr values.

Fixes #66365

Change-Id: Ic3046704825e17098f2fea5751f2959dce1073e2
Reviewed-on: https://go-review.googlesource.com/c/go/+/672915
Reviewed-by: Jonathan Amsterdam <jba@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
This commit is contained in:
Sean Liao 2025-05-14 21:26:57 +01:00 committed by Damien Neil
parent ce49eb488a
commit 3ae95aafb5
4 changed files with 55 additions and 0 deletions

1
api/next/66365.txt Normal file
View File

@ -0,0 +1 @@
pkg log/slog, func GroupAttrs(string, ...Attr) Attr #66365

View File

@ -0,0 +1 @@
[GroupAttrs] creates a group [Attr] from a slice of [Attr] values.

View File

@ -67,6 +67,15 @@ func Group(key string, args ...any) Attr {
return Attr{key, GroupValue(argsToAttrSlice(args)...)}
}
// GroupAttrs returns an Attr for a Group [Value]
// consisting of the given Attrs.
//
// GroupAttrs is a more efficient version of [Group]
// that accepts only [Attr] values.
func GroupAttrs(key string, attrs ...Attr) Attr {
return Attr{key, GroupValue(attrs...)}
}
func argsToAttrSlice(args []any) []Attr {
var (
attr Attr

View File

@ -5,6 +5,7 @@
package slog_test
import (
"context"
"log/slog"
"net/http"
"os"
@ -35,3 +36,46 @@ func ExampleGroup() {
// Output:
// level=INFO msg=finished req.method=GET req.url=localhost status=200 duration=1s
}
func ExampleGroupAttrs() {
r, _ := http.NewRequest("POST", "localhost", http.NoBody)
// ...
logger := slog.New(
slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
},
}),
)
// Use []slog.Attr to accumulate attributes.
attrs := []slog.Attr{slog.String("method", r.Method)}
attrs = append(attrs, slog.String("url", r.URL.String()))
if r.Method == "POST" {
attrs = append(attrs, slog.Int("content-length", int(r.ContentLength)))
}
// Group the attributes under a key.
logger.LogAttrs(context.Background(), slog.LevelInfo,
"finished",
slog.Int("status", http.StatusOK),
slog.GroupAttrs("req", attrs...),
)
// Groups with empty keys are inlined.
logger.LogAttrs(context.Background(), slog.LevelInfo,
"finished",
slog.Int("status", http.StatusOK),
slog.GroupAttrs("", attrs...),
)
// Output:
// level=INFO msg=finished status=200 req.method=POST req.url=localhost req.content-length=0
// level=INFO msg=finished status=200 method=POST url=localhost content-length=0
}