-
Notifications
You must be signed in to change notification settings - Fork 14
/
stats.go
109 lines (95 loc) · 2.13 KB
/
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
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
105
106
107
108
109
package stats
import (
"bufio"
"context"
"fmt"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"os"
"path/filepath"
"runtime"
"time"
)
const (
BYTE = 1 << (10 * iota)
KILOBYTE
MEGABYTE
GIGABYTE
TERABYTE
)
// EnableMemoryStatistics enables go routine that periodically prints memory
// usage of the go process.
func EnableMemoryStatistics(
ctx context.Context,
interval time.Duration,
path string,
) {
ticker := time.NewTicker(interval)
go func() {
for {
select {
case <-ticker.C:
PrintMemoryStatistics()
PrintNumOfRoutines()
case <-ctx.Done():
err := DumpPrometheusDefaults(path)
if err != nil {
fmt.Println(err)
}
return
}
}
}()
}
// toGigabytes returns given memory in bytes to gigabytes.
func toGigabytes(bytes uint64) float64 {
return float64(bytes) / GIGABYTE
}
// PrintMemoryStatistics prints memory statistics using go runtime library.
func PrintMemoryStatistics() {
var memStats runtime.MemStats
runtime.ReadMemStats(&memStats)
bytesTotalAllocated := memStats.TotalAlloc
bytesHeapAllocated := memStats.HeapAlloc
countMalloc := memStats.Mallocs
countFrees := memStats.Frees
log.Debugf(
"Total allocated: %.3fGB, Heap allocated: %.3fGB, "+
"Allocated objects count: %v, Freed objects count: %v",
toGigabytes(bytesTotalAllocated),
toGigabytes(bytesHeapAllocated),
countMalloc,
countFrees,
)
}
// DumpPrometheusDefaults write default Prometheus metrics to a file
func DumpPrometheusDefaults(path string) error {
file, err := os.OpenFile(
filepath.Join(
path,
time.Now().Format(time.RFC3339)),
os.O_APPEND|os.O_CREATE|os.O_RDWR,
0644,
)
if err != nil {
return err
}
writer := bufio.NewWriter(file)
metricFamily, err := prometheus.DefaultGatherer.Gather()
if err != nil {
return err
}
for _, v := range metricFamily {
_, err := writer.WriteString(v.String() + "\n")
if err != nil {
return err
}
}
writer.Flush()
file.Close()
return nil
}
// PrintNumOfRoutines prints number of go routines currently running
func PrintNumOfRoutines() {
log.Debugf("Num of go routines: %v\n", runtime.NumGoroutine())
}