-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathhooks.go
46 lines (39 loc) · 1.05 KB
/
hooks.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
package log
import (
"github.com/sirupsen/logrus"
)
// ContextValueFieldHook add a FieldKey=ContextValue(ContextKey) field
// (if exists) to the log entry
type ContextValueFieldHook struct {
FieldKey string // default: "context"
ContextKey string
}
func (c ContextValueFieldHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (c ContextValueFieldHook) Fire(entry *logrus.Entry) error {
//fmt.Printf("[DEBUG] ContextValueFieldHook: hook=%#v, context=%#v\n", c, entry.Context)
if c.ContextKey == "" { // nothing to do
return nil
}
if c.FieldKey == "" {
c.FieldKey = "context"
}
if entry.Context == nil {
return nil
}
value := entry.Context.Value(c.ContextKey)
if value == nil {
return nil
}
// cannot WithField in hook
//entry = entry.WithField(c.FieldKey, entry.Context.Value(c.ContextKey))
entry.Data[c.FieldKey] = entry.Context.Value(c.ContextKey)
return nil
}
// RequestIDHook add a context="request_id" field to the log entry
func RequestIDHook() logrus.Hook {
return ContextValueFieldHook{
ContextKey: "request_id",
}
}