-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContextHook.go
executable file
·98 lines (79 loc) · 1.78 KB
/
ContextHook.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package logrus_context_hook
import (
"context"
"github.com/sirupsen/logrus"
)
type ContextHook interface {
logrus.Hook
GetContextField() string
SetContextField(string)
GetContextKeys() []string
SetContextKeys([]string)
}
type contextHookImpl struct {
contextField string
contextKeys []string
}
func NewContextHook(contextField string, contextKeys []string) ContextHook {
return &contextHookImpl{
contextField: contextField,
contextKeys: contextKeys,
}
}
func (hook *contextHookImpl) GetContextField() string {
return hook.contextField
}
func (hook *contextHookImpl) SetContextField(ctxField string) {
hook.contextField = ctxField
}
func (hook *contextHookImpl) GetContextKeys() []string {
return hook.contextKeys
}
func (hook *contextHookImpl) SetContextKeys(ctxKeys []string) {
hook.contextKeys = ctxKeys
}
func (hook *contextHookImpl) Fire(entry *logrus.Entry) error {
// Context field
field := hook.contextField
if field == "*" { // if field is a wildcard
for k, v := range entry.Data {
if _, ok := v.(context.Context); ok { // find first field with value of type context, and use that.
field = k
break
}
}
}
if field == "*" {
return nil
}
// Get value
ctxCandidate, ok := entry.Data[field]
if !ok {
return nil
}
// Make sure value is of type context.Context
ctx, ok := ctxCandidate.(context.Context)
if !ok {
return nil
}
//Delete original field
delete(entry.Data, field)
for _, key := range hook.contextKeys {
value := ctx.Value(key)
if value != nil {
entry.Data[key] = value
}
}
return nil
}
// Operate on ALL levels
func (hook *contextHookImpl) Levels() []logrus.Level {
return []logrus.Level{
logrus.DebugLevel,
logrus.InfoLevel,
logrus.WarnLevel,
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
}