-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocessors.go
85 lines (70 loc) · 1.71 KB
/
processors.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
package epilog
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
const callDepth = 5
// IProcessor is an interface for processor
type IProcessor interface {
Process(entry *Entry)
}
// CalleeProcessor adds packageName and filename to entry fields
type CalleeProcessor struct {
shift int
}
// NewCalleeProcessor constructor for CalleeProcessor
func NewCalleeProcessor(shift int) *CalleeProcessor {
return &CalleeProcessor{shift: shift}
}
// Process adds two fields to entry:
// _package - name of package where logger was called
// _file - file:line where logger was called
func (p *CalleeProcessor) Process(entry *Entry) {
entry.Fields["_package"] = getPackageName(p.shift)
entry.Fields["_file"] = getFileName(p.shift)
}
func getPackageName(shift int) string {
v := "???"
if pc, _, _, ok := runtime.Caller(shift + callDepth); ok {
if f := runtime.FuncForPC(pc); f != nil {
v = formatFuncName(f.Name())
}
}
return v
}
func getFileName(shift int) string {
_, file, line, ok := runtime.Caller(shift + callDepth)
if !ok {
file = "???"
line = 0
} else {
file = filepath.Base(file)
}
return fmt.Sprintf("%s:%d", file, line)
}
func formatFuncName(f string) string {
i := strings.LastIndex(f, "/")
j := strings.Index(f[i+1:], ".")
if j < 1 {
return "???"
}
return f[:i+j+1]
}
// FieldsProcessor is a processor of fields list
type FieldsProcessor struct {
fields map[string]interface{}
}
// NewFieldsProcessor creates new FieldsProcessor
func NewFieldsProcessor(fields map[string]interface{}) *FieldsProcessor {
return &FieldsProcessor{
fields: fields,
}
}
// Process processes Entry
func (p *FieldsProcessor) Process(entry *Entry) {
for key, value := range p.fields {
entry.Fields[key] = value
}
}