forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse_log.go
334 lines (289 loc) · 9.53 KB
/
parse_log.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
package processor
import (
"fmt"
"strconv"
"time"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/types"
syslog "github.com/influxdata/go-syslog/v3"
"github.com/influxdata/go-syslog/v3/rfc3164"
"github.com/influxdata/go-syslog/v3/rfc5424"
"github.com/opentracing/opentracing-go"
)
func init() {
Constructors[TypeParseLog] = TypeSpec{
constructor: NewParseLog,
Summary: `
Parses common log [formats](#formats) into [structured data](#codecs). This is
easier and often much faster than ` + "[`grok`](/docs/components/processors/grok)" + `.`,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("format", "A common log [format](#formats) to parse.").HasOptions(
"syslog_rfc5424", "syslog_rfc3164",
),
docs.FieldCommon("codec", "Specifies the structured format to parse a log into.").HasOptions(
"json",
),
docs.FieldAdvanced("best_effort", "Still returns partially parsed messages even if an error occurs."),
docs.FieldAdvanced("allow_rfc3339", "Also accept timestamps in rfc3339 format while parsing."+
" Applicable to format `syslog_rfc3164`."),
docs.FieldAdvanced("default_year", "Sets the strategy used to set the year for rfc3164 timestamps."+
" Applicable to format `syslog_rfc3164`. When set to `current` the current year will be set, when"+
" set to an integer that value will be used. Leave this field empty to not set a default year at all."),
docs.FieldAdvanced("default_timezone", "Sets the strategy to decide the timezone for rfc3164 timestamps."+
" Applicable to format `syslog_rfc3164`. This value should follow the [time.LoadLocation](https://golang.org/pkg/time/#LoadLocation) format."),
partsFieldSpec,
},
Footnotes: `
## Codecs
Currently the only supported structured data codec is ` + "`json`" + `.
## Formats
### ` + "`syslog_rfc5424`" + `
Attempts to parse a log following the [Syslog rfc5424](https://tools.ietf.org/html/rfc5424)
spec. The resulting structured document may contain any of the following fields:
- ` + "`message`" + ` (string)
- ` + "`timestamp`" + ` (string, RFC3339)
- ` + "`facility`" + ` (int)
- ` + "`severity`" + ` (int)
- ` + "`priority`" + ` (int)
- ` + "`version`" + ` (int)
- ` + "`hostname`" + ` (string)
- ` + "`procid`" + ` (string)
- ` + "`appname`" + ` (string)
- ` + "`msgid`" + ` (string)
- ` + "`structureddata`" + ` (object)
### ` + "`syslog_rfc3164`" + `
Attempts to parse a log following the [Syslog rfc3164](https://tools.ietf.org/html/rfc3164)
spec. The resulting structured document may contain any of the following fields:
- ` + "`message`" + ` (string)
- ` + "`timestamp`" + ` (string, RFC3339)
- ` + "`facility`" + ` (int)
- ` + "`severity`" + ` (int)
- ` + "`priority`" + ` (int)
- ` + "`hostname`" + ` (string)
- ` + "`procid`" + ` (string)
- ` + "`appname`" + ` (string)
- ` + "`msgid`" + ` (string)
`,
}
}
//------------------------------------------------------------------------------
// ParseLogConfig contains configuration fields for the ParseLog processor.
type ParseLogConfig struct {
Parts []int `json:"parts" yaml:"parts"`
Format string `json:"format" yaml:"format"`
Codec string `json:"codec" yaml:"codec"`
BestEffort bool `json:"best_effort" yaml:"best_effort"`
WithRFC3339 bool `json:"allow_rfc3339" yaml:"allow_rfc3339"`
WithYear string `json:"default_year" yaml:"default_year"`
WithTimezone string `json:"default_timezone" yaml:"default_timezone"`
}
// NewParseLogConfig returns a ParseLogConfig with default values.
func NewParseLogConfig() ParseLogConfig {
return ParseLogConfig{
Parts: []int{},
Format: "syslog_rfc5424",
Codec: "json",
BestEffort: true,
WithRFC3339: true,
WithYear: "current",
WithTimezone: "UTC",
}
}
//------------------------------------------------------------------------------
type parserFormat func(body []byte) (map[string]interface{}, error)
func parserRFC5424(bestEffort bool) parserFormat {
var opts []syslog.MachineOption
if bestEffort {
opts = append(opts, rfc5424.WithBestEffort())
}
p := rfc5424.NewParser(opts...)
return func(body []byte) (map[string]interface{}, error) {
resGen, err := p.Parse(body)
if err != nil {
return nil, err
}
res := resGen.(*rfc5424.SyslogMessage)
resMap := make(map[string]interface{})
if res.Message != nil {
resMap["message"] = *res.Message
}
if res.Timestamp != nil {
resMap["timestamp"] = res.Timestamp.Format(time.RFC3339Nano)
// resMap["timestamp_unix"] = res.Timestamp().Unix()
}
if res.Facility != nil {
resMap["facility"] = *res.Facility
}
if res.Severity != nil {
resMap["severity"] = *res.Severity
}
if res.Priority != nil {
resMap["priority"] = *res.Priority
}
if res.Version != 0 {
resMap["version"] = res.Version
}
if res.Hostname != nil {
resMap["hostname"] = *res.Hostname
}
if res.ProcID != nil {
resMap["procid"] = *res.ProcID
}
if res.Appname != nil {
resMap["appname"] = *res.Appname
}
if res.MsgID != nil {
resMap["msgid"] = *res.MsgID
}
if res.StructuredData != nil {
resMap["structureddata"] = *res.StructuredData
}
return resMap, nil
}
}
func parserRFC3164(bestEffort, wrfc3339 bool, year, tz string) (parserFormat, error) {
var opts []syslog.MachineOption
if bestEffort {
opts = append(opts, rfc3164.WithBestEffort())
}
if wrfc3339 {
opts = append(opts, rfc3164.WithRFC3339())
}
switch year {
case "current":
opts = append(opts, rfc3164.WithYear(rfc3164.CurrentYear{}))
case "":
// do nothing
default:
iYear, err := strconv.Atoi(year)
if err != nil {
return nil, fmt.Errorf("failed to convert year %s into integer: %v", year, err)
}
opts = append(opts, rfc3164.WithYear(rfc3164.Year{YYYY: iYear}))
}
if tz != "" {
loc, err := time.LoadLocation(tz)
if err != nil {
return nil, fmt.Errorf("failed to lookup timezone %s - %v", loc, err)
}
opts = append(opts, rfc3164.WithTimezone(loc))
}
p := rfc3164.NewParser(opts...)
return func(body []byte) (map[string]interface{}, error) {
resGen, err := p.Parse(body)
if err != nil {
return nil, err
}
res := resGen.(*rfc3164.SyslogMessage)
resMap := make(map[string]interface{})
if res.Message != nil {
resMap["message"] = *res.Message
}
if res.Timestamp != nil {
resMap["timestamp"] = res.Timestamp.Format(time.RFC3339Nano)
// resMap["timestamp_unix"] = res.Timestamp().Unix()
}
if res.Facility != nil {
resMap["facility"] = *res.Facility
}
if res.Severity != nil {
resMap["severity"] = *res.Severity
}
if res.Priority != nil {
resMap["priority"] = *res.Priority
}
if res.Hostname != nil {
resMap["hostname"] = *res.Hostname
}
if res.ProcID != nil {
resMap["procid"] = *res.ProcID
}
if res.Appname != nil {
resMap["appname"] = *res.Appname
}
if res.MsgID != nil {
resMap["msgid"] = *res.MsgID
}
return resMap, nil
}, nil
}
func getParseFormat(parser string, bestEffort, rfc3339 bool, defYear, defTZ string) (parserFormat, error) {
switch parser {
case "syslog_rfc5424":
return parserRFC5424(bestEffort), nil
case "syslog_rfc3164":
return parserRFC3164(bestEffort, rfc3339, defYear, defTZ)
}
return nil, fmt.Errorf("format not recognised: %s", parser)
}
//------------------------------------------------------------------------------
// ParseLog is a processor that parses properly formatted messages.
type ParseLog struct {
parts []int
format parserFormat
conf Config
log log.Modular
stats metrics.Type
mCount metrics.StatCounter
mErr metrics.StatCounter
mErrJSONS metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
}
// NewParseLog returns a ParseLog processor.
func NewParseLog(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
s := &ParseLog{
parts: conf.ParseLog.Parts,
conf: conf,
log: log,
stats: stats,
mCount: stats.GetCounter("count"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
}
var err error
if s.format, err = getParseFormat(conf.ParseLog.Format, conf.ParseLog.BestEffort, conf.ParseLog.WithRFC3339,
conf.ParseLog.WithYear, conf.ParseLog.WithTimezone); err != nil {
return nil, err
}
return s, nil
}
//------------------------------------------------------------------------------
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (s *ParseLog) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
s.mCount.Incr(1)
newMsg := msg.Copy()
proc := func(index int, span opentracing.Span, part types.Part) error {
dataMap, err := s.format(part.Get())
if err != nil {
s.mErr.Incr(1)
s.log.Debugf("Failed to parse message as %s: %v\n", s.conf.ParseLog.Format, err)
return err
}
if err := newMsg.Get(index).SetJSON(dataMap); err != nil {
s.mErrJSONS.Incr(1)
s.mErr.Incr(1)
s.log.Debugf("Failed to convert log format result into json: %v\n", err)
return err
}
return nil
}
IteratePartsWithSpan(TypeParseLog, s.parts, newMsg, proc)
s.mBatchSent.Incr(1)
s.mSent.Incr(int64(newMsg.Len()))
return []types.Message{newMsg}, nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (s *ParseLog) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (s *ParseLog) WaitForClose(timeout time.Duration) error {
return nil
}
//------------------------------------------------------------------------------