Repository navigation
Expand file tree
/
Copy pathjson.go
More file actions
230 lines (216 loc) · 5 KB
/
Copy pathjson.go
File metadata and controls
230 lines (216 loc) · 5 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package logparser
import (
"encoding/json"
"io"
"strings"
"unicode/utf8"
)
const (
jsonMaxAttrs = 100
jsonMaxDepth = 8
jsonMaxValueLen = 4096
)
var (
jsonMessageKeys = map[string]int{
"msg": 0,
"message": 1,
"@m": 2,
"@mt": 3,
"body": 4,
"log": 5,
}
jsonLevelKeys = map[string]int{
"level": 0,
"severity": 1,
"loglevel": 2,
"log.level": 3,
"lvl": 4,
"@l": 5,
"severity_text": 6,
"levelname": 7,
}
jsonTimestampKeys = map[string]bool{
"time": true, "timestamp": true, "ts": true, "t": true, "@t": true, "@timestamp": true, "datetime": true, "asctime": true,
}
)
type JsonLog struct {
Level Level
Message string
Attributes map[string]string
}
func ParseJsonLog(content string) *JsonLog {
fields := decodeJsonObject(content)
if fields == nil {
return nil
}
return jsonLogFromFields(fields)
}
// decodeJsonObject decodes a log line that holds a single, non-empty JSON
// object, or returns nil. Surrounding whitespace, such as the \r of a CRLF
// line ending, is ignored. Numbers are kept as json.Number.
func decodeJsonObject(content string) map[string]any {
content = strings.TrimSpace(content)
if len(content) < 2 || content[0] != '{' || content[len(content)-1] != '}' {
return nil
}
d := json.NewDecoder(strings.NewReader(content))
d.UseNumber()
var fields map[string]any
if d.Decode(&fields) != nil || len(fields) == 0 {
return nil
}
if _, err := d.Token(); err != io.EOF {
return nil
}
return fields
}
// jsonLogFromFields extracts the message, level and attributes from a decoded
// JSON log line.
func jsonLogFromFields(fields map[string]any) *JsonLog {
res := &JsonLog{Attributes: map[string]string{}}
var msgKey, lvlKey string
var msgPrio, lvlPrio int
var msgVal string
var lvlRaw any
for k, v := range fields {
lk := strings.ToLower(k)
if p, ok := jsonMessageKeys[lk]; ok {
if s, ok := v.(string); ok {
if msgKey == "" || p < msgPrio || (p == msgPrio && k < msgKey) {
if msgKey != "" {
flattenJsonField(msgKey, msgVal, res.Attributes, jsonMaxDepth)
}
msgKey, msgPrio, msgVal = k, p, s
} else {
flattenJsonField(k, v, res.Attributes, jsonMaxDepth)
}
continue
}
} else if p, ok := jsonLevelKeys[lk]; ok {
if lvl := jsonLevelFromValue(v); lvl != LevelUnknown {
if lvlKey == "" || p < lvlPrio || (p == lvlPrio && k < lvlKey) {
if lvlKey != "" {
flattenJsonField(lvlKey, lvlRaw, res.Attributes, jsonMaxDepth)
}
lvlKey, lvlPrio, lvlRaw = k, p, v
res.Level = lvl
} else {
flattenJsonField(k, v, res.Attributes, jsonMaxDepth)
}
continue
}
} else if jsonTimestampKeys[lk] && jsonIsTimestampValue(v) {
continue
}
flattenJsonField(k, v, res.Attributes, jsonMaxDepth)
}
res.Message = strings.TrimSuffix(msgVal, "\n")
return res
}
func jsonIsTimestampValue(v any) bool {
switch value := v.(type) {
case string, json.Number:
return true
case map[string]any:
if len(value) != 1 {
return false
}
if _, ok := value["$date"]; ok { // mongodb
return true
}
}
return false
}
func jsonLevelFromValue(v any) Level {
switch value := v.(type) {
case string:
return jsonLevelFromString(value)
case json.Number:
return jsonLevelFromNumber(value)
}
return LevelUnknown
}
func flattenJsonField(key string, value any, attrs map[string]string, depth int) {
if len(attrs) >= jsonMaxAttrs {
return
}
switch v := value.(type) {
case nil:
attrs[key] = ""
case string:
attrs[key] = truncateUtf8(v, jsonMaxValueLen)
case bool:
if v {
attrs[key] = "true"
} else {
attrs[key] = "false"
}
case json.Number:
attrs[key] = v.String()
case map[string]any:
if depth <= 0 {
attrs[key] = jsonEncode(v)
return
}
for k, vv := range v {
flattenJsonField(key+"."+k, vv, attrs, depth-1)
}
default:
attrs[key] = jsonEncode(v)
}
}
func jsonEncode(v any) string {
data, err := json.Marshal(v)
if err != nil {
return ""
}
return truncateUtf8(string(data), jsonMaxValueLen)
}
func truncateUtf8(s string, limit int) string {
if len(s) <= limit {
return s
}
for limit > 0 && !utf8.RuneStart(s[limit]) {
limit--
}
return s[:limit]
}
func jsonLevelFromString(s string) Level {
if len(s) > 16 {
return LevelUnknown
}
switch strings.ToLower(s) {
case "trace", "trc", "debug", "dbg", "verbose":
return LevelDebug
case "info", "inf", "information", "informational", "notice":
return LevelInfo
case "warn", "wrn", "warning":
return LevelWarning
case "error", "err":
return LevelError
case "fatal", "ftl", "critical", "crit", "panic", "dpanic", "alert", "emerg", "emergency":
return LevelCritical
}
return LevelUnknown
}
func jsonLevelFromNumber(n json.Number) Level {
v, err := n.Int64()
if err != nil {
return LevelUnknown
}
switch {
case v < 10:
return LevelUnknown
case v < 30:
return LevelDebug
case v < 40:
return LevelInfo
case v < 50:
return LevelWarning
case v < 60:
return LevelError
case v < 100:
return LevelCritical
}
return LevelUnknown
}