-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
88 lines (68 loc) · 1.61 KB
/
parser.go
File metadata and controls
88 lines (68 loc) · 1.61 KB
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
package main
import (
"fmt"
"maps"
"slices"
"sort"
"strings"
"github.com/fatih/color"
"github.com/tidwall/gjson"
)
var (
dimStyle = color.New(color.Faint)
boldStyle = color.New(color.Bold)
)
func processLine(line string, cfg *config, formatTime func(string) string) string {
trimmed := strings.TrimSpace(line)
if len(trimmed) == 0 || trimmed[0] != '{' {
return line
}
parsed := gjson.Parse(trimmed)
if parsed.Type != gjson.JSON {
return line
}
keys := make(map[string]string)
flatten(parsed, "", keys, cfg.exclude)
var b strings.Builder
if ts, ok := keys[cfg.tsField]; ok {
delete(keys, cfg.tsField)
b.WriteString(dimStyle.Sprint(formatTime(ts)))
b.WriteByte(' ')
}
if lvl, ok := keys[cfg.levelField]; ok {
delete(keys, cfg.levelField)
b.WriteString(formatLevel(lvl))
b.WriteByte(' ')
}
if msg, ok := keys[cfg.msgField]; ok {
delete(keys, cfg.msgField)
b.WriteString(boldStyle.Sprint(msg))
}
keySlice := slices.Collect(maps.Keys(keys))
sort.Strings(keySlice)
for _, key := range keySlice {
val := keys[key]
_, _ = fmt.Fprintf(&b, " %s=%s", coloredKey(key), val)
}
return b.String()
}
func flatten(result gjson.Result, prefix string, out map[string]string, exclude map[string]struct{}) {
switch {
case result.IsObject():
result.ForEach(func(key, value gjson.Result) bool {
newKey := key.String()
if prefix != "" {
newKey = prefix + "." + newKey
}
if _, ok := exclude[newKey]; ok {
return true
}
flatten(value, newKey, out, exclude)
return true
})
case result.IsArray():
out[prefix] = result.Raw
default:
out[prefix] = result.String()
}
}