-
Notifications
You must be signed in to change notification settings - Fork 2
/
filter.go
112 lines (108 loc) · 2.44 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
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
103
104
105
106
107
108
109
110
111
112
package pfxlog
import (
"bufio"
"encoding/json"
"fmt"
"github.com/mgutz/ansi"
"io"
"strings"
"time"
)
func Filter(sourceR io.Reader, options *Options) {
r := bufio.NewReader(sourceR)
var last time.Time
lastSet := false
for {
line, err := r.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
line = autocut(line)
msg := make(map[string]interface{})
err = json.Unmarshal([]byte(line), &msg)
if err != nil {
fmt.Println(ansi.Yellow + strings.TrimSpace(line) + ansi.DefaultFG)
continue
}
stamp, err := time.Parse(time.RFC3339, msg["time"].(string))
if err != nil {
panic(err)
}
if !lastSet {
last = stamp
lastSet = true
}
delta := stamp.Sub(last).Seconds()
var level string
switch msg["level"].(string) {
case "panic":
level = options.PanicLabel
case "fatal":
level = options.FatalLabel
case "error":
level = options.ErrorLabel
case "warning":
level = options.WarningLabel
case "info":
level = options.InfoLabel
case "debug":
level = options.DebugLabel
case "trace":
level = options.TraceLabel
default:
panic(fmt.Errorf("unknown (%s)", msg["level"].(string)))
}
var prefix string
if v, found := msg["func"]; found {
prefix = strings.TrimPrefix(v.(string), options.TrimPrefix)
}
if context, found := msg["_context"]; found {
prefix += " [" + context.(string) + "]"
}
message := msg["msg"].(string)
data := data(msg)
if len(data) > 0 {
fields := "{"
field := 0
for k, v := range data {
if field > 0 {
fields += " "
}
field++
fields += fmt.Sprintf("%s=[%v]", k, v)
}
fields += "} "
message = options.FieldsColor + fields + options.DefaultFgColor + message
}
var fmtTs string
if options.AbsoluteTime {
fmtTs = fmt.Sprintf("[%s]", stamp.Format(options.PrettyTimestampFormat))
} else {
fmtTs = fmt.Sprintf("[%8.3f]", delta)
}
fmt.Printf("%s %s %s: %s\n",
options.TimestampColor+fmtTs+options.DefaultFgColor,
level,
options.FunctionColor+prefix+options.DefaultFgColor,
message)
}
}
func data(in map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{})
for k, v := range in {
if k != "level" && k != "func" && k != "file" && k != "msg" && k != "time" && k != "_context" {
out[k] = v
}
}
return out
}
func autocut(inputLine string) string {
idx := strings.IndexRune(inputLine, '{')
if idx > -1 {
return inputLine[idx:]
}
return inputLine
}