-
Notifications
You must be signed in to change notification settings - Fork 26
/
processor.go
102 lines (84 loc) · 1.99 KB
/
processor.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
99
100
101
102
package slog
import (
"crypto/md5"
"encoding/hex"
"os"
"runtime"
"github.com/gookit/goutil/strutil"
)
//
// Processor interface
//
// Processor interface definition
type Processor interface {
// Process record
Process(record *Record)
}
// ProcessorFunc wrapper definition
type ProcessorFunc func(record *Record)
// Process record
func (fn ProcessorFunc) Process(record *Record) {
fn(record)
}
// ProcessableHandler interface
type ProcessableHandler interface {
// AddProcessor add a processor
AddProcessor(Processor)
// ProcessRecord handle a record
ProcessRecord(record *Record)
}
// Processable definition
type Processable struct {
processors []Processor
}
// AddProcessor to the handler
func (p *Processable) AddProcessor(processor Processor) {
p.processors = append(p.processors, processor)
}
// ProcessRecord process record
func (p *Processable) ProcessRecord(r *Record) {
// processing log record
for _, processor := range p.processors {
processor.Process(r)
}
}
//
// there are some built-in processors
//
// AddHostname to record
func AddHostname() Processor {
hostname, _ := os.Hostname()
return ProcessorFunc(func(record *Record) {
record.AddField("hostname", hostname)
})
}
// AddUniqueID to record
func AddUniqueID(fieldName string) Processor {
hs := md5.New()
return ProcessorFunc(func(record *Record) {
rb, _ := strutil.RandomBytes(32)
hs.Write(rb)
randomID := hex.EncodeToString(hs.Sum(nil))
hs.Reset()
record.AddField(fieldName, randomID)
})
}
// MemoryUsage get memory usage.
var MemoryUsage ProcessorFunc = func(record *Record) {
stat := new(runtime.MemStats)
runtime.ReadMemStats(stat)
record.SetExtraValue("memoryUsage", stat.Alloc)
}
// AppendCtxKeys append context keys to record.Fields
func AppendCtxKeys(keys ...string) Processor {
return ProcessorFunc(func(record *Record) {
if record.Ctx == nil {
return
}
for _, key := range keys {
if val := record.Ctx.Value(key); val != nil {
record.AddField(key, record.Ctx.Value(key))
}
}
})
}