-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
prometheus.go
64 lines (49 loc) · 1.32 KB
/
prometheus.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
package metrics
import (
"fmt"
"net/http"
"strconv"
"strings"
)
const (
prometheusNamespace = "anycable_go"
)
// Prometheus returns metrics info in Prometheus format
func (m *Metrics) Prometheus() string {
var buf strings.Builder
tags := toPromTags(m.tags)
m.EachCounter(func(counter *Counter) {
name := prometheusNamespace + `_` + counter.Name()
buf.WriteString(
"\n# HELP " + name + " " + counter.Desc() + "\n",
)
buf.WriteString("# TYPE " + name + " counter\n")
buf.WriteString(name + tags + " " + strconv.FormatUint(counter.Value(), 10) + "\n")
})
m.EachGauge(func(gauge *Gauge) {
name := prometheusNamespace + `_` + gauge.Name()
buf.WriteString(
"\n# HELP " + name + " " + gauge.Desc() + "\n",
)
buf.WriteString("# TYPE " + name + " gauge\n")
buf.WriteString(name + tags + " " + strconv.FormatUint(gauge.Value(), 10) + "\n")
})
return buf.String()
}
// PrometheusHandler is provide metrics to the world
func (m *Metrics) PrometheusHandler(w http.ResponseWriter, r *http.Request) {
metricsData := m.Prometheus()
fmt.Fprint(w, metricsData)
}
func toPromTags(tags map[string]string) string {
if tags == nil {
return ""
}
buf := make([]string, len(tags))
i := 0
for k, v := range tags {
buf[i] = fmt.Sprintf("%s=\"%s\"", k, v)
i++
}
return fmt.Sprintf("{%s}", strings.Join(buf, ", "))
}