-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
77 lines (67 loc) · 2.02 KB
/
metrics.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
package metrics
import (
"log"
"net/http"
"strconv"
"time"
"github.com/metal-toolbox/fleet-rest-skeleton/internal/app"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
apiLatencySeconds *prometheus.HistogramVec
dependencyErrorCount *prometheus.CounterVec
)
func init() {
dependencyErrorCount = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: app.AppName,
Subsystem: "dependencies",
Name: "errors_total",
Help: "a count of all errors attempting to reach " + app.AppName + " dependencies",
}, []string{
"dependency_name",
"operation",
},
)
apiLatencySeconds = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: app.AppName,
Subsystem: "api",
Name: "latency_seconds",
Help: "api latency measurements in seconds",
// XXX: will need to tune these buckets once we understand common behaviors better
// buckets between 25ms to 10 s
Buckets: []float64{0.025, 0.05, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0},
}, []string{
"endpoint",
"response_code",
},
)
}
// ListenAndServeMetrics exposes prometheus metrics as /metrics on port 9090
func ListenAndServe() {
endpoint := "0.0.0.0:9090"
go func() {
http.Handle("/metrics", promhttp.Handler())
server := &http.Server{
Addr: endpoint,
ReadHeaderTimeout: 2 * time.Second,
}
if err := server.ListenAndServe(); err != nil {
log.Println(err)
}
}()
}
// DependencyError provides a convenience method to hide some prometheus implementation
// details.
func DependencyError(name, operation string) {
dependencyErrorCount.WithLabelValues(name, operation).Inc()
}
// APICallEpilog observes the results and latency of an API call
func APICallEpilog(start time.Time, endpoint string, responseCode int) {
code := strconv.Itoa(responseCode)
elapsed := time.Since(start).Seconds()
apiLatencySeconds.WithLabelValues(endpoint, code).Observe(elapsed)
}