-
Notifications
You must be signed in to change notification settings - Fork 7
/
log_record.go
356 lines (291 loc) · 8.99 KB
/
log_record.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
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"github.com/gookit/goutil/strutil"
"github.com/pkg/errors"
"github.com/qiangyt/jog/config"
"github.com/qiangyt/jog/util"
)
// LogRecordT ...
type LogRecordT struct {
LineNo int
Prefix string
StandardFields map[string]FieldValue
UnknownFields map[string]util.AnyValue
Raw string
Unknown bool
StartupLine bool
}
// LogRecord .
type LogRecord = *LogRecordT
// PrintElement ...
func (i LogRecord) PrintElement(cfg config.Configuration, element util.Printable, builder *strings.Builder, a string) {
var color util.Color
if cfg.Colorization {
if i.StartupLine {
color = cfg.StartupLine.Color
} else {
color = element.GetColor(a)
}
} else {
color = nil
}
element.PrintTo(color, builder, a)
}
// PopulateOtherFields ...
func (i LogRecord) PopulateOtherFields(cfg config.Configuration, unknownFields map[string]util.AnyValue, implicitStandardFields map[string]FieldValue, result map[string]string) {
if !cfg.HasOthersFieldInPattern {
return
}
nameElement := cfg.Fields.Others.Name
separatorElement := cfg.Fields.Others.Separator
unknownFieldValueElement := cfg.Fields.Others.Value
// sort field names
var fNames []string
for fName := range unknownFields {
fNames = append(fNames, fName)
}
for fName := range implicitStandardFields {
fNames = append(fNames, fName)
}
sort.Strings(fNames)
builder := &strings.Builder{}
first := true
for _, fName := range fNames {
fValueUnknown := unknownFields[fName]
if fValueUnknown != nil {
if !first {
builder.WriteString(", ")
}
first = false
i.PrintElement(cfg, nameElement, builder, fName)
i.PrintElement(cfg, separatorElement, builder, "=")
i.PrintElement(cfg, unknownFieldValueElement, builder, fValueUnknown.String())
} else {
fValueImplicit := implicitStandardFields[fName]
if !fValueImplicit.Config.IsEnabled() {
continue
}
if !first {
builder.WriteString(", ")
}
first = false
i.PrintElement(cfg, nameElement, builder, fName)
i.PrintElement(cfg, separatorElement, builder, "=")
i.PrintElement(cfg, fValueImplicit.Config, builder, fValueImplicit.Output)
}
}
result["others"] = builder.String()
}
// PopulateExplicitStandardFields ...
func (i LogRecord) PopulateExplicitStandardFields(cfg config.Configuration, explicitStandardFields map[string]FieldValue, result map[string]string) {
for _, f := range explicitStandardFields {
builder := &strings.Builder{}
i.PrintElement(cfg, f.Config, builder, f.Output)
result[f.Config.Name] = builder.String()
}
}
// AsFlatLine ...
func (i LogRecord) AsFlatLine(cfg config.Configuration) string {
builder := &strings.Builder{}
i.PrintElement(cfg, cfg.LineNo, builder, fmt.Sprintf("%-6v ", i.LineNo))
if i.Unknown {
i.PrintElement(cfg, cfg.UnknownLine, builder, i.Raw)
} else {
if len(i.Prefix) > 0 {
i.PrintElement(cfg, cfg.Prefix, builder, strutil.MustString(i.Prefix))
}
explicitStandardFields, implicitStandardFields := i.ExtractStandardFields(cfg)
result := make(map[string]string)
i.PopulateOtherFields(cfg, i.UnknownFields, implicitStandardFields, result)
i.PopulateExplicitStandardFields(cfg, explicitStandardFields, result)
builder.WriteString(os.Expand(cfg.Pattern, func(fieldName string) string {
return result[fieldName]
}))
}
if i.StartupLine {
startupLine := &strings.Builder{}
cfg.StartupLine.PrintTo(cfg.StartupLine.Color, startupLine, builder.String())
builder = startupLine
}
return builder.String()
}
// ExtractStandardFields ...
func (i LogRecord) ExtractStandardFields(cfg config.Configuration) (map[string]FieldValue, map[string]FieldValue) {
explicts := make(map[string]FieldValue)
implicits := make(map[string]FieldValue)
for n, f := range i.StandardFields {
if cfg.HasFieldInPattern(n) {
explicts[n] = f
} else {
implicits[n] = f
}
}
return explicts, implicits
}
// MatchesLevelFilter ...
func (i LogRecord) MatchesLevelFilter(cfg config.Configuration, levelFilters []config.Enum) bool {
levelFieldValue := i.StandardFields["level"]
if levelFieldValue != nil {
levelFieldEnum := levelFieldValue.enumValue
for _, levelFilter := range levelFilters {
if levelFieldEnum == levelFilter {
return true
}
}
}
return false
}
// MatchesTimestampFilter ...
func (i LogRecord) MatchesTimestampFilter(cfg config.Configuration, beforeFilter *time.Time, afterFilter *time.Time) bool {
timestampFieldValue := i.StandardFields["timestamp"]
if timestampFieldValue != nil {
timestampValue := timestampFieldValue.timeValue
beforeMatches := true
if beforeFilter != nil {
beforeMatches = timestampValue.Before(*beforeFilter) || timestampValue.Equal(*beforeFilter)
}
afterMatches := true
if afterFilter != nil {
afterMatches = timestampValue.After(*afterFilter) || timestampValue.Equal(*afterFilter)
}
return beforeMatches && afterMatches
}
return false
}
// MatchesFilters ...
func (i LogRecord) MatchesFilters(cfg config.Configuration, options Options) bool {
levelFilters := options.GetLevelFilters()
if len(options.levelFilters) > 0 {
if !i.MatchesLevelFilter(cfg, levelFilters) {
return false
}
}
if options.HasTimestampFilter() {
if !i.MatchesTimestampFilter(cfg, options.BeforeFilter, options.AfterFilter) {
return false
}
}
return true
}
func isStartupLine(cfg config.Configuration, raw string) bool {
contains := cfg.StartupLine.Contains
return len(contains) > 0 && strings.Contains(raw, contains)
}
func tryToParseUsingGrok(cfg config.Configuration, options Options, lineNo int, line string) (matchesGrok bool, prefix string, standardFields map[string]FieldValue, unknownFields map[string]util.AnyValue) {
prefix = ""
standardFields = map[string]FieldValue{}
unknownFields = map[string]util.AnyValue{}
if options.isGrokEnabled() == false {
matchesGrok = false
return
}
standardsFieldConfig := cfg.Fields.StandardsWithAllAliases
grok := cfg.Grok
for _, pattern := range options.GrokPatterns {
fields, err := grok.Parse(pattern, line)
if err != nil {
//TODO: debug log
} else {
for fName, fValue := range fields {
v := util.AnyValueFromRaw(lineNo, fValue, cfg.Replace)
fConfig, contains := standardsFieldConfig[fName]
if contains {
fName = fConfig.Name // normalize field name
standardFields[fName] = NewFieldValue(cfg, options, fConfig, v)
} else {
unknownFields[fName] = v
}
}
if len(standardFields) == 0 {
continue
}
matchesGrok = true
for _, matchesFieldName := range grok.MatchesFields {
if _, contains := standardFields[matchesFieldName]; contains == false {
matchesGrok = false
break
}
}
if matchesGrok {
return
}
}
}
return
}
func tryToParseAsJSON(cfg config.Configuration, options Options, lineNo int, line string) (isJSON bool, prefix string, standardFields map[string]FieldValue, unknownFields map[string]util.AnyValue) {
prefix = ""
standardFields = map[string]FieldValue{}
unknownFields = map[string]util.AnyValue{}
posOfLeftBracket := strings.IndexByte(line, '{')
if posOfLeftBracket < 0 {
log.Printf("line %d is not JSON line: <%s>\n", lineNo, line)
isJSON = false
return
}
if posOfLeftBracket > 0 {
prefix = line[:posOfLeftBracket]
line = line[posOfLeftBracket:]
}
allFields := make(map[string]interface{})
if err := json.Unmarshal([]byte(line), &allFields); err != nil {
log.Printf("parse round 1 failed: line %d: <%s>\n\treason %v\n", lineNo, line, errors.Wrap(err, ""))
line = strings.ReplaceAll(line, "\\\"", "\"")
line = strings.ReplaceAll(line, "\t", " ")
if err := json.Unmarshal([]byte(line), &allFields); err != nil {
log.Printf("parse round 2 failed: line %d: <%s>\n\treason %v\n", lineNo, line, errors.Wrap(err, ""))
isJSON = false
return
}
}
standardsFieldConfig := cfg.Fields.StandardsWithAllAliases
for fName, fValue := range allFields {
v := util.AnyValueFromRaw(lineNo, fValue, cfg.Replace)
fConfig, contains := standardsFieldConfig[fName]
if contains {
fName = fConfig.Name // normalize field name
standardFields[fName] = NewFieldValue(cfg, options, fConfig, v)
} else {
unknownFields[fName] = v
}
}
isJSON = true
return
}
// ParseAsRecord ...
func ParseAsRecord(cfg config.Configuration, options Options, lineNo int, rawLine string) LogRecord {
r := &LogRecordT{
LineNo: lineNo,
UnknownFields: make(map[string]util.AnyValue),
StandardFields: make(map[string]FieldValue),
Raw: rawLine,
Unknown: true,
StartupLine: isStartupLine(cfg, rawLine),
}
line := strings.TrimSpace(rawLine)
if len(line) == 0 {
log.Printf("line %d is blank\n", lineNo)
return r
}
var isJSON bool
var matchesGrok bool
isJSON, r.Prefix, r.StandardFields, r.UnknownFields = tryToParseAsJSON(cfg, options, lineNo, line)
if isJSON {
r.Unknown = false
} else {
matchesGrok, r.Prefix, r.StandardFields, r.UnknownFields = tryToParseUsingGrok(cfg, options, lineNo, line)
if matchesGrok {
r.Unknown = false
} else {
r.Unknown = true
}
}
return r
}