Skip to content

Commit 4397029

Browse files
committed
slog: context
Support putting a Logger into a context.Context and getting it out. Also, remove concat3 since it wasn't used, and generalize concat. Change-Id: Ibdac8c163bd8f8f3d3c4d54bbe54f0f80bfdaa98 Reviewed-on: https://go-review.googlesource.com/c/exp/+/429437 Run-TryBot: Jonathan Amsterdam <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent 91042ec commit 4397029

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

slog/context.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright 2022 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package slog
6+
7+
import "context"
8+
9+
type contextKey struct{}
10+
11+
// NewContext returns a context that contains the given Logger.
12+
// Use FromContext to retrieve the Logger.
13+
func NewContext(ctx context.Context, l *Logger) context.Context {
14+
return context.WithValue(ctx, contextKey{}, l)
15+
}
16+
17+
// FromContext returns the Logger stored in ctx by NewContext, or the default
18+
// Logger if there is none.
19+
func FromContext(ctx context.Context) *Logger {
20+
if l, ok := ctx.Value(contextKey{}).(*Logger); ok {
21+
return l
22+
}
23+
return Default()
24+
}

slog/util.go

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,13 @@
44

55
package slog
66

7-
func concat(l1, l2 []Attr) []Attr {
8-
return concat3(l1, l2, nil)
9-
}
10-
11-
func concat3(l1, l2, l3 []Attr) []Attr {
12-
l := make([]Attr, len(l1)+len(l2)+len(l3))
13-
copy(l, l1)
14-
copy(l[len(l1):], l2)
15-
copy(l[len(l1)+len(l2):], l3)
16-
return l
7+
// concat returns a new slice with the elements of s1 followed
8+
// by those of s2. The slice has no additional capacity.
9+
func concat[T any](s1, s2 []T) []T {
10+
s := make([]T, len(s1)+len(s2))
11+
copy(s, s1)
12+
copy(s[len(s1):], s2)
13+
return s
1714
}
1815

1916
// Cheap integer to fixed-width decimal ASCII. Give a negative width to avoid zero-padding.

0 commit comments

Comments
 (0)