-
Notifications
You must be signed in to change notification settings - Fork 1
/
logr.go
56 lines (44 loc) · 1.18 KB
/
logr.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
package logr
import (
"context"
)
type Logger interface {
// Start start span for tracing
//
// ctx log = logr.Start(ctx, "SpanName")
// defer log.End()
//
Start(ctx context.Context, name string, keyAndValues ...any) (context.Context, Logger)
// End end span
End()
// WithValues key value pairs
WithValues(keyAndValues ...any) Logger
// Debug debug info
Debug(msg string, args ...any)
// Info info
Info(msg string, args ...any)
// Warn
Warn(err error)
// Error
Error(err error)
}
type contextKey struct{}
func WithLogger(ctx context.Context, logger Logger) context.Context {
return context.WithValue(ctx, contextKey{}, logger)
}
func FromContext(ctx context.Context) Logger {
if v, ok := ctx.Value(contextKey{}).(Logger); ok {
return v
}
return Discard()
}
func Start(ctx context.Context, name string, keyAndValues ...any) (context.Context, Logger) {
return FromContext(ctx).Start(ctx, name, keyAndValues...)
}
func LoggerFromContext(ctx context.Context) (Logger, bool) {
v, ok := ctx.Value(contextKey{}).(Logger)
return v, ok
}
func LoggerInjectContext(ctx context.Context, logger Logger) context.Context {
return context.WithValue(ctx, contextKey{}, logger)
}