From e72a19d7689fc2ca2cfd7ecaaf66cff54a2dbb26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=B7=E6=BA=AA?= Date: Thu, 21 Oct 2021 17:20:38 +0800 Subject: [PATCH] fix(srvhttp): RequestDurationSeconds shouldn't panic when missing labels (#207) --- srvhttp/metrics.go | 23 ++++++++++++++++------- srvhttp/metrics_test.go | 8 ++++++++ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/srvhttp/metrics.go b/srvhttp/metrics.go index 0bb3218e..187b636b 100644 --- a/srvhttp/metrics.go +++ b/srvhttp/metrics.go @@ -46,17 +46,17 @@ type RequestDurationSeconds struct { // Histogram is the underlying histogram of RequestDurationSeconds. Histogram metrics.Histogram - // labels - module string - service string - route string + // labels has been set + module bool + service bool + route bool } // Module specifies the module label for RequestDurationSeconds. func (r *RequestDurationSeconds) Module(module string) *RequestDurationSeconds { return &RequestDurationSeconds{ Histogram: r.Histogram.With("module", module), - module: module, + module: true, service: r.service, route: r.route, } @@ -67,7 +67,7 @@ func (r *RequestDurationSeconds) Service(service string) *RequestDurationSeconds return &RequestDurationSeconds{ Histogram: r.Histogram.With("service", service), module: r.module, - service: service, + service: true, route: r.route, } } @@ -78,11 +78,20 @@ func (r *RequestDurationSeconds) Route(route string) *RequestDurationSeconds { Histogram: r.Histogram.With("route", route), module: r.module, service: r.service, - route: route, + route: true, } } // Observe records the time taken to process the request. func (r *RequestDurationSeconds) Observe(seconds float64) { + if !r.module { + r.Histogram = r.Histogram.With("module", "") + } + if !r.service { + r.Histogram = r.Histogram.With("service", "") + } + if !r.route { + r.Histogram = r.Histogram.With("route", "") + } r.Histogram.Observe(seconds) } diff --git a/srvhttp/metrics_test.go b/srvhttp/metrics_test.go index 79a6634e..c0f51350 100644 --- a/srvhttp/metrics_test.go +++ b/srvhttp/metrics_test.go @@ -27,3 +27,11 @@ func TestRequestDurationSeconds(t *testing.T) { h.ServeHTTP(nil, httptest.NewRequest(http.MethodGet, "/", nil)) assert.GreaterOrEqual(t, 1.0, rds.Histogram.(*generic.Histogram).Quantile(0.5)) } + +func TestRequestDurationSeconds_noPanicWhenMissingLabels(t *testing.T) { + rds := &RequestDurationSeconds{ + Histogram: generic.NewHistogram("foo", 2), + } + rds.Observe(50) + assert.ElementsMatch(t, []string{"module", "", "service", "", "route", ""}, rds.Histogram.(*generic.Histogram).LabelValues()) +}