Skip to content

Commit

Permalink
slog: implement argsToAttrs directly
Browse files Browse the repository at this point in the history
Now that we have argsToAttr (singular), we can easily construct
a slice of Attr without going through Record.

Change-Id: I3175316fef1997a6063140fcfe499c174e6d3071
Reviewed-on: https://go-review.googlesource.com/c/exp/+/430095
Run-TryBot: Jonathan Amsterdam <[email protected]>
Reviewed-by: Alan Donovan <[email protected]>
  • Loading branch information
jba committed Sep 15, 2022
1 parent 82e28ad commit d6a8ba4
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions slog/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,24 @@ func (l *Logger) Handler() Handler { return l.handler }
// With returns a new Logger whose handler's attributes are a concatenation of
// l's attributes and the given arguments, converted to Attrs as in
// [Logger.Log].
func (l *Logger) With(attrs ...any) *Logger {
return &Logger{handler: l.handler.With(argsToAttrs(attrs))}
}

func argsToAttrs(args []any) []Attr {
var r Record
setAttrs(&r, args)
return r.Attrs()
func (l *Logger) With(args ...any) *Logger {
var (
attr Attr
attrs []Attr
)
for len(args) > 0 {
attr, args = argsToAttr(args)
attrs = append(attrs, attr)
}
return &Logger{handler: l.handler.With(attrs)}
}

// New creates a new Logger with the given Handler.
func New(h Handler) *Logger { return &Logger{handler: h} }

// With calls Logger.With on the default logger.
func With(attrs ...any) *Logger {
return Default().With(attrs...)
func With(args ...any) *Logger {
return Default().With(args...)
}

// Enabled reports whether l emits log records at the given level.
Expand Down Expand Up @@ -138,7 +140,7 @@ func setAttrs(r *Record, args []any) {
}
}

// argsToAttrs turns a prefix of the args slice into an Attr and returns
// argsToAttr turns a prefix of the args slice into an Attr and returns
// the unused portion of the slice.
// If args[0] is an Attr, it returns it.
// If args[0] is a string, it treats the first two elements as
Expand Down

0 comments on commit d6a8ba4

Please sign in to comment.