Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

log/slog: add WithAttrs and Logger.WithAttrs #66938

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/log/slog/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,16 @@ func (l *Logger) With(args ...any) *Logger {
return c
}

// WithAttrs is a more efficient version of [Logger.With] that accepts only Attrs.
func (l *Logger) WithAttrs(attrs ...Attr) *Logger {
if len(attrs) == 0 {
return l
}
c := l.clone()
c.handler = l.handler.WithAttrs(attrs)
return c
}

// WithGroup returns a Logger that starts a group, if name is non-empty.
// The keys of all attributes added to the Logger will be qualified by the given
// name. (How that qualification happens depends on the [Handler.WithGroup]
Expand Down Expand Up @@ -161,6 +171,11 @@ func With(args ...any) *Logger {
return Default().With(args...)
}

// WithAttrs calls [Logger.WithAttrs] on the default logger.
func WithAttrs(attrs ...Attr) *Logger {
return Default().WithAttrs(attrs...)
}

// Enabled reports whether l emits log records at the given context and level.
func (l *Logger) Enabled(ctx context.Context, level Level) bool {
if ctx == nil {
Expand Down
9 changes: 5 additions & 4 deletions src/log/slog/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,11 @@ func TestAttrs(t *testing.T) {

l1 := New(&captureHandler{}).With("a", 1)
l2 := New(l1.Handler()).With("b", 2)
l2.Info("m", "c", 3)
h := l2.Handler().(*captureHandler)
check(h.attrs, Int("a", 1), Int("b", 2))
check(attrsSlice(h.r), Int("c", 3))
l3 := New(l2.Handler()).WithAttrs(Int("c", 3))
l3.Info("m", "d", 4)
h := l3.Handler().(*captureHandler)
check(h.attrs, Int("a", 1), Int("b", 2), Int("c", 3))
check(attrsSlice(h.r), Int("d", 4))
}

func TestCallDepth(t *testing.T) {
Expand Down