-
Notifications
You must be signed in to change notification settings - Fork 43
/
metrics.go
72 lines (62 loc) · 2.01 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
package bootstrap
import (
"net/http"
"strconv"
"time"
"github.com/openfaas/faas-provider/httputil"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
// httpMetrics is for recording R.E.D. metrics for system endpoint calls
// for HTTP status code, method, duration and path.
type httpMetrics struct {
// RequestsTotal is a Prometheus counter vector partitioned by method and status.
RequestsTotal *prometheus.CounterVec
// RequestDurationHistogram is a Prometheus summary vector partitioned by method and status.
RequestDurationHistogram *prometheus.HistogramVec
}
// newHttpMetrics initialises a new httpMetrics struct for
// recording R.E.D. metrics for system endpoint calls
func newHttpMetrics() *httpMetrics {
return &httpMetrics{
RequestsTotal: promauto.NewCounterVec(prometheus.CounterOpts{
Subsystem: "provider",
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
}, []string{"code", "method", "path"}),
RequestDurationHistogram: promauto.NewHistogramVec(prometheus.HistogramOpts{
Subsystem: "provider",
Name: "http_request_duration_seconds",
Help: "Seconds spent serving HTTP requests.",
Buckets: prometheus.DefBuckets,
}, []string{"code", "method", "path"}),
}
}
func (hm *httpMetrics) InstrumentHandler(next http.Handler, pathOverride string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ww := httputil.NewHttpWriteInterceptor(w)
next.ServeHTTP(ww, r)
duration := time.Since(start)
path := r.URL.Path
if len(pathOverride) > 0 {
path = pathOverride
}
defer func() {
hm.RequestsTotal.With(
prometheus.Labels{"code": strconv.Itoa(ww.Status()),
"method": r.Method,
"path": path,
}).
Inc()
}()
defer func() {
hm.RequestDurationHistogram.With(
prometheus.Labels{"code": strconv.Itoa(ww.Status()),
"method": r.Method,
"path": path,
}).
Observe(duration.Seconds())
}()
}
}