-
Notifications
You must be signed in to change notification settings - Fork 352
/
metrics_middleware.go
37 lines (33 loc) · 1.02 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
package api
import (
"net/http"
"strconv"
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/routers/legacy"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/treeverse/lakefs/pkg/httputil"
)
func MetricsMiddleware(swagger *openapi3.Swagger) func(http.Handler) http.Handler {
// router for operation ID lookup
router, err := legacy.NewRouter(swagger)
if err != nil {
panic(err)
}
return func(next http.Handler) http.Handler {
// request histogram by operation ID
requestHistogramHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route, _, err := router.FindRoute(r)
start := time.Now()
mrw := httputil.NewMetricResponseWriter(w)
next.ServeHTTP(mrw, r)
if err == nil {
requestHistograms.
WithLabelValues(route.Operation.OperationID, strconv.Itoa(mrw.StatusCode)).
Observe(time.Since(start).Seconds())
}
})
// request handler
return promhttp.InstrumentHandlerCounter(requestCounter, requestHistogramHandler)
}
}