forked from tsaikd/gogstash
-
Notifications
You must be signed in to change notification settings - Fork 1
/
filterjson.go
81 lines (70 loc) · 1.98 KB
/
filterjson.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
package filterjson
import (
"context"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/tsaikd/gogstash/config"
"github.com/tsaikd/gogstash/config/goglog"
"github.com/tsaikd/gogstash/config/logevent"
)
// ModuleName is the name used in config file
const ModuleName = "json"
// ErrorTag tag added to event when process module failed
const ErrorTag = "gogstash_filter_json_error"
// FilterConfig holds the configuration json fields and internal objects
type FilterConfig struct {
config.FilterConfig
Msgfield string `json:"message"`
Appendkey string `json:"appendkey"`
Tsfield string `json:"timestamp"`
Tsformat string `json:"timeformat"`
}
// DefaultFilterConfig returns an FilterConfig struct with default values
func DefaultFilterConfig() FilterConfig {
return FilterConfig{
FilterConfig: config.FilterConfig{
CommonConfig: config.CommonConfig{
Type: ModuleName,
},
},
}
}
// InitHandler initialize the filter plugin
func InitHandler(ctx context.Context, raw *config.ConfigRaw) (config.TypeFilterConfig, error) {
conf := DefaultFilterConfig()
if err := config.ReflectConfig(raw, &conf); err != nil {
return nil, err
}
return &conf, nil
}
// Event the main filter event
func (f *FilterConfig) Event(ctx context.Context, event logevent.LogEvent) logevent.LogEvent {
var parsedMessage map[string]interface{}
if err := jsoniter.Unmarshal([]byte(event.Message), &parsedMessage); err != nil {
event.AddTag(ErrorTag)
goglog.Logger.Error(err)
return event
}
if f.Appendkey != "" {
event.SetValue(f.Appendkey, parsedMessage)
} else {
if event.Extra == nil {
event.Extra = make(map[string]interface{})
}
for key, value := range parsedMessage {
switch key {
case f.Msgfield:
event.Message = value.(string)
case f.Tsfield:
if ts, err := time.Parse(f.Tsformat, value.(string)); err == nil {
event.Timestamp = ts
}
case logevent.TagsField:
event.ParseTags(value)
default:
event.Extra[key] = value
}
}
}
return event
}