forked from hashicorp/go-eventlogger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
57 lines (47 loc) · 1.14 KB
/
formatter.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package eventlogger
import (
"bytes"
"context"
"encoding/json"
"time"
)
const (
JSONFormat = "json"
)
// JSONFormatter is a Formatter Node which formats the Event as JSON.
type JSONFormatter struct{}
var _ Node = &JSONFormatter{}
// Process formats the Event as JSON and stores that formatted data in
// Event.Formatted with a key of "json"
func (w *JSONFormatter) Process(ctx context.Context, e *Event) (*Event, error) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
err := enc.Encode(struct {
CreatedAt time.Time `json:"created_at"`
EventType `json:"event_type"`
Payload interface{} `json:"payload"`
}{
e.CreatedAt,
e.Type,
e.Payload,
})
if err != nil {
return nil, err
}
e.FormattedAs(JSONFormat, buf.Bytes())
return e, nil
}
// Reopen is a no op
func (w *JSONFormatter) Reopen() error {
return nil
}
// Type describes the type of the node as a Formatter.
func (w *JSONFormatter) Type() NodeType {
return NodeTypeFormatter
}
// Name returns a representation of the Formatter's name
func (w *JSONFormatter) Name() string {
return "JSONFormatter"
}