-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfilter.go
69 lines (61 loc) · 1.76 KB
/
filter.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
package log
import (
"runtime/debug"
"time"
)
// Filter is a function that is used to manipulate the Data passed to a Logger.
// This could be adding fields, removing fields, or even setting the Data to
// nil. Filters need to be able to accept nil Data, as that is the most
// effective way of stopping Data from being logged.
type Filter func(lvl, threshold Level, data Data) Data
var (
// DefaultTimestampFormat is used by the BaseFilter to add timestamps to logs.
DefaultTimestampFormat = "2006-01-02T15:04:05.000Z"
// DefaultFilter sets the BaseFilter to be enabled by default.
DefaultFilter = BaseFilter()
)
// BaseFilter provides a Filter that prevents logs above the set threshold from
// being logged, and adds a timestamp, version, and log level to the log Data.
func BaseFilter() Filter {
return func(lvl, threshold Level, data Data) Data {
if data == nil {
return nil
}
if lvl <= TraceLevel && lvl > threshold {
return nil
}
data["@timestamp"] = time.Now().UTC().Format(DefaultTimestampFormat)
data["@version"] = "1"
data["log_level"] = lvl
return data
}
}
// StackFilter adds a stack trace to log data when the log level exceeds the threshold.
func StackFilter(stackLevel Level) Filter {
return func(lvl, threshold Level, data Data) Data {
if data == nil {
return nil
}
if lvl <= stackLevel {
data["_stack"] = string(debug.Stack())
}
return data
}
}
// ErrorFilter ensures that raw errors in Data with specified keys are correctly
// displayed.
func ErrorFilter(errorKeys ...string) Filter {
return func(lvl, threshold Level, data Data) Data {
for _, key := range errorKeys {
err, exists := data[key]
if !exists {
continue
}
val, ok := err.(error)
if ok {
data[key] = val.Error()
}
}
return data
}
}