-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathlog.go
More file actions
76 lines (61 loc) · 1.57 KB
/
log.go
File metadata and controls
76 lines (61 loc) · 1.57 KB
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
67
68
69
70
71
72
73
74
75
76
package bklog
import (
"context"
"runtime/debug"
"github.com/containerd/containerd/log"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/trace"
)
func init() {
// overwrites containerd/log
log.G = GetLogger
log.L = L
}
var (
G = GetLogger
L = logrus.NewEntry(logrus.StandardLogger())
)
var (
logWithTraceID = false
)
func EnableLogWithTraceID(b bool) {
logWithTraceID = b
}
type (
loggerKey struct{}
)
// WithLogger returns a new context with the provided logger. Use in
// combination with logger.WithField(s) for great effect.
func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
return context.WithValue(ctx, loggerKey{}, logger)
}
// GetLogger retrieves the current logger from the context. If no logger is
// available, the default logger is returned.
func GetLogger(ctx context.Context) (l *logrus.Entry) {
logger := ctx.Value(loggerKey{})
if logger != nil {
l = logger.(*logrus.Entry)
} else if logger := log.GetLogger(ctx); logger != nil {
l = logger
} else {
l = L
}
if logWithTraceID {
if spanContext := trace.SpanFromContext(ctx).SpanContext(); spanContext.IsValid() {
return l.WithFields(logrus.Fields{
"traceID": spanContext.TraceID(),
"spanID": spanContext.SpanID(),
})
}
}
return l
}
// LazyStackTrace lets you include a stack trace as a field's value in a log but only
// call it when the log level is actually enabled.
type LazyStackTrace struct{}
func (LazyStackTrace) String() string {
return string(debug.Stack())
}
func (LazyStackTrace) MarshalText() ([]byte, error) {
return debug.Stack(), nil
}