From c4ff0ab1b7501a66732cd923f999032f4f3ffe32 Mon Sep 17 00:00:00 2001 From: Daan Sprenkels Date: Sun, 16 May 2021 20:24:00 +0200 Subject: [PATCH] Add request_duration_seconds metric --- metrics.go | 24 +++++++++++++++++++++++- router.go | 5 +++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/metrics.go b/metrics.go index 0df6acf..d3b629e 100644 --- a/metrics.go +++ b/metrics.go @@ -17,7 +17,7 @@ const metricNamespace = "rushlink" // metricURLsTotalGauge counts the number of requests that are handled by // the application, partitioned by status code and HTTP method. // -// This counter is updated by throughout the application. +// This counter is updated by the router. var metricRequestsTotalCounter = prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: metricNamespace, @@ -26,6 +26,27 @@ var metricRequestsTotalCounter = prometheus.NewCounterVec( Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", }, []string{"code", "method"}) +// metricRequestsLatencyNanoSeconds keeps track of the request latencies for +// each http request. +// +// This historogram is updated by the router. +var metricRequestsLatencyNanoSeconds = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: metricNamespace, + Subsystem: "http", + Name: "request_duration_seconds", + Buckets: []float64{ + float64(500e-6), + float64(1e-3), + float64(2e-3), + float64(5e-3), + float64(10e-3), + float64(20e-3), + float64(50e-3), + }, + Help: "The latency of each HTTP request, partitioned by status code and HTTP method.", + }, []string{"code", "method"}) + // metricURLsTotalGauge measures the amount of pastes stored in the database, // partitioned by type and state. // @@ -41,6 +62,7 @@ var metricURLsTotalGauge = prometheus.NewGaugeVec( // StartMetricsServer starts sering Prometheus metrics exports on addr func StartMetricsServer(addr string, database *db.Database, fs *db.FileStore) { prometheus.MustRegister(metricRequestsTotalCounter) + prometheus.MustRegister(metricRequestsLatencyNanoSeconds) prometheus.MustRegister(metricURLsTotalGauge) router := mux.NewRouter() diff --git a/router.go b/router.go index d9e5df4..6e888a3 100644 --- a/router.go +++ b/router.go @@ -58,13 +58,18 @@ func (rl *rushlink) recoveryMiddleware(next http.Handler) http.Handler { func (rl *rushlink) metricsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tick := time.Now() srw := statusResponseWriter{Inner: w} next.ServeHTTP(&srw, r) + tock := time.Now() status := strconv.Itoa(srw.StatusCode) labels := map[string]string{"code": status, "method": r.Method} // Update requests counter metric metricRequestsTotalCounter.With(labels).Inc() + // Update request latency metric + elapsed := tock.Sub(tick) + metricRequestsLatencyNanoSeconds.With(labels).Observe(elapsed.Seconds()) }) }