-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeacon.go
104 lines (90 loc) · 2.35 KB
/
beacon.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
102
103
104
package beacon // import "github.com/section-io/beacon"
import (
"bytes"
"encoding/json"
"io"
"os"
)
//TODO export struct instead of interface https://github.com/golang/go/wiki/CodeReviewComments#interfaces
type Event interface {
AddContext(key, value string) Event
AddAnnotation(key, value string) Event
SetCorrelationID(id string) Event
WriteToStderr() error
}
type event struct {
Label string `json:"label"`
Severity Severity `json:"severity"`
Metric metric `json:"metric"`
Context map[string]string `json:"context,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
CorrelationID string `json:"correlationId,omitempty"`
}
type metric struct {
Type MetricType `json:"type"`
Value float64 `json:"value"`
}
func NewEvent(label string, severity Severity, metricType MetricType, metricValue float64) Event {
return &event{
Label: label,
Severity: severity,
Metric: metric{
Type: metricType,
Value: metricValue,
},
}
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}
// Convenience method to beacon a single count-type info event, panics if there is a resulting error
func BeaconSingleInfoCount(label string, annotations map[string]string) Event {
ev := NewEvent(
label,
Info,
Count,
1,
)
for k, v := range annotations {
ev.AddAnnotation(k, v)
}
err := ev.WriteToStderr()
panicOnError(err)
return ev
}
func (e *event) AddContext(key, value string) Event {
if e.Context == nil {
e.Context = make(map[string]string)
}
e.Context[key] = value
return e
}
func (e *event) AddAnnotation(key, value string) Event {
if e.Annotations == nil {
e.Annotations = make(map[string]string)
}
e.Annotations[key] = value
return e
}
func (e *event) SetCorrelationID(id string) Event {
e.CorrelationID = id
return e
}
func (e event) writeKubernetesBeaconLine(w io.Writer) error {
// Use a Buffer to ensure we only call w.Write() once.
buf := bytes.NewBufferString("section.io-beacon:")
enc := json.NewEncoder(buf)
// Encode writes ... to the stream, followed by a newline character.
// https://golang.org/pkg/encoding/json/#Encoder.Encode
err := enc.Encode(e)
if err != nil {
return err
}
_, err = w.Write(buf.Bytes())
return err
}
func (e event) WriteToStderr() error {
return e.writeKubernetesBeaconLine(os.Stderr)
}