-
Notifications
You must be signed in to change notification settings - Fork 17
/
runtime_emitter.go
63 lines (52 loc) · 1.73 KB
/
runtime_emitter.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
package runtimeemitter
import (
"runtime"
"time"
"code.cloudfoundry.org/go-loggregator/v2"
)
// Sender is the interface of the client that can be used to emit gauge
// metrics.
type Sender interface {
EmitGauge(opts ...v2.EmitGaugeOption)
}
// Emitter will emit a gauge with runtime stats via the sender on the given
// interval. default interval is 15 seconds.
type Emitter struct {
interval time.Duration
sender Sender
}
// RuntimeEmitterOption is the option provides configuration for an Emitter.
type RuntimeEmitterOption func(e *Emitter)
// WithInterval returns a RuntimeEmitterOption to configure the interval at
// which the runtime emitter emits gauges.
func WithInterval(d time.Duration) RuntimeEmitterOption {
return func(e *Emitter) {
e.interval = d
}
}
// New returns an Emitter that is configured with the given sender and
// RuntimeEmitterOptions.
func New(sender Sender, opts ...RuntimeEmitterOption) *Emitter {
e := &Emitter{
sender: sender,
interval: 10 * time.Second,
}
for _, o := range opts {
o(e)
}
return e
}
// Run starts the ticker with the configured interval and emits a gauge on
// that interval. This method will block but the user may run in a go routine.
func (e *Emitter) Run() {
for range time.Tick(e.interval) {
memstats := &runtime.MemStats{}
runtime.ReadMemStats(memstats)
e.sender.EmitGauge(
v2.WithGaugeValue("memoryStats.numBytesAllocatedHeap", float64(memstats.HeapAlloc), "Bytes"),
v2.WithGaugeValue("memoryStats.numBytesAllocatedStack", float64(memstats.StackInuse), "Bytes"),
v2.WithGaugeValue("memoryStats.lastGCPauseTimeNS", float64(memstats.PauseNs[(memstats.NumGC+255)%256]), "ns"),
v2.WithGaugeValue("numGoRoutines", float64(runtime.NumGoroutine()), "Count"),
)
}
}