/
metrics_middleware.go
52 lines (40 loc) · 1.43 KB
/
metrics_middleware.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
package middlewares
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"net/http"
"strconv"
)
var (
statusCodeCounter = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "cloud_connector_http_status_code_counter",
Help: "The number of http status codes per interface",
}, []string{"status_code"})
httpResponseDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "cloud_connector_http_response_duration",
Help: "The amount of time the http request took to process",
}, []string{"status_code"})
)
// MetricsMiddleware allows the passage of parameters into the metrics middleware
type MetricsMiddleware struct {
}
func (mw *MetricsMiddleware) RecordHTTPMetrics(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
resp := &wrappedResponseWriter{w, 200}
httpResponseTimer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
httpResponseDuration.WithLabelValues(strconv.Itoa(resp.statusCode)).Observe(v)
}))
defer httpResponseTimer.ObserveDuration()
next.ServeHTTP(resp, req)
statusCodeCounter.With(prometheus.Labels{
"status_code": strconv.Itoa(resp.statusCode)}).Inc()
})
}
type wrappedResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (ww *wrappedResponseWriter) WriteHeader(status int) {
ww.statusCode = status
ww.ResponseWriter.WriteHeader(status)
}