forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 7
/
console.go
86 lines (73 loc) · 1.51 KB
/
console.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
package console
import (
"encoding/json"
"os"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/op"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
)
func init() {
outputs.RegisterOutputPlugin("console", New)
}
type console struct {
config config
}
func New(config *common.Config, _ int) (outputs.Outputer, error) {
c := &console{config: defaultConfig}
err := config.Unpack(&c.config)
if err != nil {
return nil, err
}
return c, nil
}
func newConsole(pretty bool) *console {
return &console{config{pretty}}
}
func writeBuffer(buf []byte) error {
written := 0
for written < len(buf) {
n, err := os.Stdout.Write(buf[written:])
if err != nil {
return err
}
written += n
}
return nil
}
// Implement Outputer
func (c *console) Close() error {
return nil
}
func (c *console) PublishEvent(
s op.Signaler,
opts outputs.Options,
event common.MapStr,
) error {
var jsonEvent []byte
var err error
if c.config.Pretty {
jsonEvent, err = json.MarshalIndent(event, "", " ")
} else {
jsonEvent, err = json.Marshal(event)
}
if err != nil {
logp.Err("Fail to convert the event to JSON (%v): %#v", err, event)
op.SigCompleted(s)
return err
}
if err = writeBuffer(jsonEvent); err != nil {
goto fail
}
if err = writeBuffer([]byte{'\n'}); err != nil {
goto fail
}
op.SigCompleted(s)
return nil
fail:
if opts.Guaranteed {
logp.Critical("Unable to publish events to console: %v", err)
}
op.SigFailed(s, err)
return err
}