-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcontext.go
58 lines (52 loc) · 1.48 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
package log
import "context"
const (
ctxLogger ctxKey = iota + 1
)
// Context initializes a context for logging.
func Context(ctx context.Context, opts ...LogOption) context.Context {
l, ok := ctx.Value(ctxLogger).(*logger)
if !ok {
l = &logger{options: defaultOptions()}
}
l.lock.Lock()
defer l.lock.Unlock()
for _, opt := range opts {
opt(l.options)
}
if l.options.disableBuffering != nil && l.options.disableBuffering(ctx) {
l.flush()
}
return context.WithValue(ctx, ctxLogger, l)
}
// WithContext will inject the second context in the given one.
//
// It is useful when building middleware handlers such as log.HTTP
func WithContext(parentCtx, logCtx context.Context) context.Context {
logger, ok := logCtx.Value(ctxLogger).(*logger)
if !ok {
return parentCtx
}
return context.WithValue(parentCtx, ctxLogger, logger)
}
// MustContainLogger will panic if the given context is missing the logger.
//
// It can be used during server initialisation when you have a function or
// middleware that you want to ensure receives a context with a logger.
func MustContainLogger(logCtx context.Context) {
_, ok := logCtx.Value(ctxLogger).(*logger)
if !ok {
panic("provided a context without a logger. Use log.Context")
}
}
// DebugEnabled returns true if the given context has debug logging enabled.
func DebugEnabled(ctx context.Context) bool {
v := ctx.Value(ctxLogger)
if v == nil {
return false
}
l := v.(*logger)
l.lock.Lock()
defer l.lock.Unlock()
return l.options.debug
}