-
Notifications
You must be signed in to change notification settings - Fork 15
/
runtime_stats.go
65 lines (55 loc) · 1.49 KB
/
runtime_stats.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
package runtime_stats
import (
"log"
"runtime"
"time"
"github.com/cloudfoundry/sonde-go/events"
"google.golang.org/protobuf/proto"
)
type EventEmitter interface {
Emit(events.Event) error
}
type RuntimeStats struct {
emitter EventEmitter
interval time.Duration
}
func NewRuntimeStats(emitter EventEmitter, interval time.Duration) *RuntimeStats {
return &RuntimeStats{
emitter: emitter,
interval: interval,
}
}
func (rs *RuntimeStats) Run(stopChan <-chan struct{}) {
ticker := time.NewTicker(rs.interval)
defer ticker.Stop()
for {
rs.emit("numCPUS", float64(runtime.NumCPU()))
rs.emit("numGoRoutines", float64(runtime.NumGoroutine()))
rs.emitMemMetrics()
select {
case <-ticker.C:
case <-stopChan:
return
}
}
}
func (rs *RuntimeStats) emitMemMetrics() {
stats := new(runtime.MemStats)
runtime.ReadMemStats(stats)
rs.emit("memoryStats.numBytesAllocatedHeap", float64(stats.HeapAlloc))
rs.emit("memoryStats.numBytesAllocatedStack", float64(stats.StackInuse))
rs.emit("memoryStats.numBytesAllocated", float64(stats.Alloc))
rs.emit("memoryStats.numMallocs", float64(stats.Mallocs))
rs.emit("memoryStats.numFrees", float64(stats.Frees))
rs.emit("memoryStats.lastGCPauseTimeNS", float64(stats.PauseNs[(stats.NumGC+255)%256]))
}
func (rs *RuntimeStats) emit(name string, value float64) {
err := rs.emitter.Emit(&events.ValueMetric{
Name: &name,
Value: &value,
Unit: proto.String("count"),
})
if err != nil {
log.Printf("RuntimeStats: failed to emit: %v", err)
}
}