aboutsummaryrefslogtreecommitdiff
path: root/internal/middleware/metrics.go
blob: f9d7e0f71f8b620e68d74089b6d199db0033bb14 (plain)
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
package middleware

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	requestCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "handler_requests_total",
			Help: "Total number of request/responses by HTTP status code.",
		}, []string{"handler", "code"})

	requestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
		Name: "handler_request_duration",
		Help: "Handler request duration.",
	}, []string{"handler", "method"})

	requestInFlight = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: "handler_requests_in_flight",
		Help: "Current number of requests being served.",
	}, []string{"handler"})
)

func init() {
	_ = prometheus.Register(requestCounter)
	_ = prometheus.Register(requestDuration)
	_ = prometheus.Register(requestInFlight)
}

// Metrics captures request duration, request count and in-flight request count
// metrics for HTTP handlers. The family field is used to discriminate handlers.
func Metrics(family string, next http.Handler) http.Handler {
	return promhttp.InstrumentHandlerDuration(
		requestDuration.MustCurryWith(prometheus.Labels{"handler": family}),
		promhttp.InstrumentHandlerCounter(requestCounter.MustCurryWith(prometheus.Labels{"handler": family}),
			promhttp.InstrumentHandlerInFlight(requestInFlight.With(prometheus.Labels{"handler": family}), next),
		),
	)
}