-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
66 lines (52 loc) · 1.37 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cslog
import (
"context"
"log/slog"
)
func FromContext(ctx context.Context, slog *slog.Logger) context.Context {
return context.WithValue(ctx, slogKey, slog)
}
func FromBackground(slog *slog.Logger) context.Context {
return FromContext(context.Background(), slog)
}
func Logger(ctx context.Context) *slog.Logger {
l, ok := ctx.Value(slogKey).(*slog.Logger)
if !ok || l == nil {
return slog.Default()
}
return l
}
type slogKeyT struct{}
var slogKey slogKeyT
func WithAttrs(ctx context.Context, attr ...slog.Attr) context.Context {
l := buildLogger(ctx, attr...)
return FromContext(ctx, l)
}
func WithGroup(ctx context.Context, g string) context.Context {
l := Logger(ctx)
l = l.WithGroup(g)
return FromContext(ctx, l)
}
func Debug(ctx context.Context, msg string, args ...slog.Attr) {
l := buildLogger(ctx, args...)
l.DebugContext(ctx, msg)
}
func Info(ctx context.Context, msg string, args ...slog.Attr) {
l := buildLogger(ctx, args...)
l.InfoContext(ctx, msg)
}
func Warn(ctx context.Context, msg string, args ...slog.Attr) {
l := buildLogger(ctx, args...)
l.WarnContext(ctx, msg)
}
func Error(ctx context.Context, msg string, args ...slog.Attr) {
l := buildLogger(ctx, args...)
l.ErrorContext(ctx, msg)
}
func buildLogger(ctx context.Context, args ...slog.Attr) *slog.Logger {
l := Logger(ctx)
for _, arg := range args {
l = l.With(arg)
}
return l
}