forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.go
101 lines (85 loc) · 1.97 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
98
99
100
101
package console
import (
"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"
"github.com/elastic/beats/libbeat/outputs/codecs/json"
)
func init() {
outputs.RegisterOutputPlugin("console", New)
}
type console struct {
out *os.File
codec outputs.Codec
}
func New(_ string, config *common.Config, _ int) (outputs.Outputer, error) {
var unpackedConfig Config
err := config.Unpack(&unpackedConfig)
if err != nil {
return nil, err
}
var codec outputs.Codec
if unpackedConfig.Codec.Namespace.IsSet() {
codec, err = outputs.CreateEncoder(unpackedConfig.Codec)
if err != nil {
return nil, err
}
} else {
codec = json.New(unpackedConfig.Pretty)
}
c, err := newConsole(codec)
if err != nil {
return nil, fmt.Errorf("console output initialization failed with: %v", 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(codec outputs.Codec) (*console, error) {
return &console{codec: codec, out: os.Stdout}, nil
}
// Implement Outputer
func (c *console) Close() error {
return nil
}
var nl = []byte{'\n'}
func (c *console) PublishEvent(
s op.Signaler,
opts outputs.Options,
data outputs.Data,
) error {
serializedEvent, err := c.codec.Encode(data.Event)
if err = c.writeBuffer(serializedEvent); err != nil {
goto fail
}
if err = c.writeBuffer(nl); 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
}