-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
63 lines (55 loc) · 1.78 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
package log
import "context"
type logContextType string
// ContextKeyLogFields is the key for the logging fields context value.
const ContextKeyLogFields logContextType = "nrfta/go-log/Fields"
// WithContext initializes context with a logging fields stack with the given fields. If the given
// context has already bene initialized, then the fields are pushed onto the existing stack.
func WithContext(parent context.Context, fields ...Field) context.Context {
if parent.Value(ContextKeyLogFields) != nil {
PushContextFields(parent, fields...)
return parent
}
return context.WithValue(parent, ContextKeyLogFields, makeFieldStack().push(fields))
}
// PushContextFields pushes the given fields onto the logging fields stack.
func PushContextFields(ctx context.Context, fields ...Field) {
stack := getStack(ctx)
if stack == nil {
return
}
stack.push(fields)
}
// PopContextFields pops the last entry off of the logging fields stack.
func PopContextFields(ctx context.Context) {
stack := getStack(ctx)
if stack == nil {
return
}
stack.pop()
}
// GetContextFields retrieves the logging `Fields` from context. GetContextFields returns an empty Fields map
// if the context has not been initialized by calling WithContext.
func GetContextFields(ctx context.Context, additionalFields ...Field) Fields {
stack := getStack(ctx)
if stack == nil {
return make(Fields)
}
fields := stack.allFields()
for _, f := range additionalFields {
fields[f.Name] = f.Value
}
return fields
}
func getStack(ctx context.Context) *fieldStack {
stackObj := ctx.Value(ContextKeyLogFields)
if stackObj == nil {
Warn("context logging fields not initialized; call log.WithContext")
return nil
}
stack, ok := stackObj.(*fieldStack)
if !ok {
Warn("context logging fields has incorrect type")
}
return stack
}