Skip to content

Commit

Permalink
logg/slog: avoid allocates in fromCtx
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed Nov 16, 2024
1 parent 69ad881 commit 29005a7
Showing 1 changed file with 28 additions and 12 deletions.
40 changes: 28 additions & 12 deletions slog/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -1130,27 +1130,43 @@ func (s *Entry) WithContextKeys(keys ...any) *Entry {
func (s *Entry) ctxKeysWanted() bool { return len(s.contextKeys) > 0 }
func (s *Entry) ctxKeys() []any { return s.contextKeys }
func (s *Entry) fromCtx(ctx context.Context) (ret Attrs) {
mu := make(map[string]struct{})
for _, k := range s.ctxKeys() {
if v := ctx.Value(k); v != nil {
switch key := k.(type) {
case Stringer:
kk := key.String()
if _, ok := mu[kk]; !ok {
ret = append(ret, &kvp{kk, v})
mu[kk] = struct{}{}
if ctxKeysUnify {
mu := make(map[string]struct{})
for _, k := range s.ctxKeys() {
if v := ctx.Value(k); v != nil {
switch key := k.(type) {
case Stringer:
kk := key.String()
if _, ok := mu[kk]; !ok {
ret = append(ret, &kvp{kk, v})
mu[kk] = struct{}{}
}
case string:
if _, ok := mu[key]; !ok {
ret = append(ret, &kvp{key, v})
mu[key] = struct{}{}
}
}
case string:
if _, ok := mu[key]; !ok {
}
}
} else {
for _, k := range s.ctxKeys() {
if v := ctx.Value(k); v != nil {
switch key := k.(type) {
case Stringer:
kk := key.String()
ret = append(ret, &kvp{kk, v})
case string:
ret = append(ret, &kvp{key, v})
mu[key] = struct{}{}
}
}
}
}
return
}

const ctxKeysUnify = false

// var poolHelper = Pool(
// newPrintCtx,
// func(ctx *PrintCtx, i int) []byte {
Expand Down

0 comments on commit 29005a7

Please sign in to comment.