forked from humanlogio/humanlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
71 lines (62 loc) · 1.68 KB
/
handler.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
package humanlog
import (
"time"
"github.com/humanlogio/humanlog/internal/pkg/config"
"github.com/kr/logfmt"
)
// Handler can recognize it's log lines, parse them and prettify them.
type Handler interface {
CanHandle(line []byte) bool
Prettify(skipUnchanged bool) []byte
logfmt.Handler
}
var DefaultOptions = func() *HandlerOptions {
opts := &HandlerOptions{
TimeFields: []string{"time", "ts", "@timestamp", "timestamp", "Timestamp"},
MessageFields: []string{"message", "msg", "Body"},
LevelFields: []string{"level", "lvl", "loglevel", "severity", "SeverityText"},
timeNow: time.Now,
}
return opts
}
type HandlerOptions struct {
TimeFields []string
MessageFields []string
LevelFields []string
timeNow func() time.Time
}
var _ = HandlerOptionsFrom(config.DefaultConfig) // ensure it's valid
func HandlerOptionsFrom(cfg config.Config) *HandlerOptions {
opts := DefaultOptions()
if cfg.TimeFields != nil {
opts.TimeFields = appendUnique(opts.TimeFields, *cfg.TimeFields)
}
if cfg.MessageFields != nil {
opts.MessageFields = appendUnique(opts.MessageFields, *cfg.MessageFields)
}
if cfg.LevelFields != nil {
opts.LevelFields = appendUnique(opts.LevelFields, *cfg.LevelFields)
}
return opts
}
func appendUnique(a []string, b []string) []string {
// init with `len(b)` because usually `a` will be
// nil at first, but `b` wont be
seen := make(map[string]struct{}, len(b))
out := make([]string, 0, len(b))
for _, aa := range a {
if _, ok := seen[aa]; ok {
continue
}
seen[aa] = struct{}{}
out = append(out, aa)
}
for _, bb := range b {
if _, ok := seen[bb]; ok {
continue
}
seen[bb] = struct{}{}
out = append(out, bb)
}
return out
}