-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
59 lines (51 loc) · 2.08 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
package golog
import "context"
// LevelDecider is implemented to decide
// if a Level is active together with a given context.
type LevelDecider interface {
// IsActive returns if a Level is active together with a given context.
// It's valid to pass a nil context.
IsActive(context.Context, Level) bool
}
var deciderCtxKey int
// ContextWithLevelDecider returns a new context with the passed LevelDecider
// added to the parent.
// Logger methods with a context argument and known level will
// check if the passed context has a LevelDecider and call
// its IsActive method to decide if the following message should be logged.
// See also IsActiveContext.
//
// LevelFilter implements LevelDecider and can be added directly to a context.
// Disable all levels below the default info configuration for a context:
//
// ctx = golog.ContextWithLevelDecider(ctx, log.Levels.Info.FilterOutBelow())
func ContextWithLevelDecider(parent context.Context, decider LevelDecider) context.Context {
return context.WithValue(parent, &deciderCtxKey, decider)
}
// ContextWithoutLogging returns a new context with logging
// disabled for all levels.
func ContextWithoutLogging(parent context.Context) context.Context {
return ContextWithLevelDecider(parent, BoolLevelDecider(false))
}
// IsActiveContext returns true by default except when a
// LevelDecider was added to the context using ContextWithLevelDecider,
// then the result of its IsActive method will be returned.
// It's valid to pass a nil context which will return true.
func IsActiveContext(ctx context.Context, level Level) bool {
if ctx == nil {
return true
}
if decider, _ := ctx.Value(&deciderCtxKey).(LevelDecider); decider != nil {
return decider.IsActive(ctx, level)
}
return true
}
// BoolLevelDecider implements LevelDecider by
// always returning the underlying bool value from its IsActive method
// independent of the arguments.
type BoolLevelDecider bool
// IsActive always returns the underlying bool value of the receiver
// independent of the arguments.
func (b BoolLevelDecider) IsActive(context.Context, Level) bool {
return bool(b)
}