forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.go
90 lines (75 loc) · 1.66 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
87
88
89
90
package console
import (
"encoding/json"
"fmt"
"os"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
)
func init() {
outputs.RegisterOutputPlugin("console", plugin{})
}
type plugin struct{}
func (p plugin) NewOutput(
config *outputs.MothershipConfig,
topologyExpire int,
) (outputs.Outputer, error) {
pretty := config.Pretty != nil && *config.Pretty
c := newConsole(pretty)
// check stdout actually being available
if _, err := c.out.Stat(); err != nil {
return nil, fmt.Errorf("console output initialization failed with: %v", err)
}
return c, nil
}
type console struct {
pretty bool
out *os.File
}
func newConsole(pretty bool) *console {
return &console{pretty: pretty, out: os.Stdout}
}
func (c *console) PublishEvent(
s outputs.Signaler,
opts outputs.Options,
event common.MapStr,
) error {
var jsonEvent []byte
var err error
if c.pretty {
jsonEvent, err = json.MarshalIndent(event, "", " ")
} else {
jsonEvent, err = json.Marshal(event)
}
if err != nil {
logp.Err("Fail to convert the event to JSON: %s", err)
outputs.SignalCompleted(s)
return err
}
if err = c.writeBuffer(jsonEvent); err != nil {
goto fail
}
if err = c.writeBuffer([]byte{'\n'}); err != nil {
goto fail
}
outputs.SignalCompleted(s)
return nil
fail:
if opts.Guaranteed {
logp.Critical("Unable to publish events to console: %v", err)
}
outputs.SignalFailed(s, err)
return err
}
func (c *console) writeBuffer(buf []byte) error {
written := 0
for written < len(buf) {
n, err := c.out.Write(buf[written:])
if err != nil {
return err
}
written += n
}
return nil
}