This repository has been archived by the owner on Dec 21, 2019. It is now read-only.
forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.go
97 lines (82 loc) · 1.82 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
91
92
93
94
95
96
97
package console
import (
"encoding/json"
"fmt"
"os"
"runtime"
"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
out *os.File
}
func New(_ string, config *common.Config, _ int) (outputs.Outputer, error) {
c := &console{config: defaultConfig, out: os.Stdout}
err := config.Unpack(&c.config)
if err != nil {
return nil, err
}
// check stdout actually being available
if runtime.GOOS != "windows" {
if _, err = c.out.Stat(); err != nil {
return nil, fmt.Errorf("console output initialization failed with: %v", err)
}
}
return c, nil
}
func newConsole(pretty bool) *console {
return &console{config: config{pretty}, out: os.Stdout}
}
// Implement Outputer
func (c *console) Close() error {
return nil
}
func (c *console) PublishEvent(
s op.Signaler,
opts outputs.Options,
data outputs.Data,
) error {
var jsonEvent []byte
var err error
if c.config.Pretty {
jsonEvent, err = json.MarshalIndent(data.Event, "", " ")
} else {
jsonEvent, err = json.Marshal(data.Event)
}
if err != nil {
logp.Err("Fail to convert the event to JSON (%v): %#v", err, data.Event)
op.SigCompleted(s)
return err
}
if err = c.writeBuffer(jsonEvent); err != nil {
goto fail
}
if err = c.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
}
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
}