Skip to content

Commit e72a19d

Browse files
authored
fix(srvhttp): RequestDurationSeconds shouldn't panic when missing labels (#207)
1 parent ab0fffc commit e72a19d

2 files changed

Lines changed: 24 additions & 7 deletions

File tree

srvhttp/metrics.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,17 @@ type RequestDurationSeconds struct {
4646
// Histogram is the underlying histogram of RequestDurationSeconds.
4747
Histogram metrics.Histogram
4848

49-
// labels
50-
module string
51-
service string
52-
route string
49+
// labels has been set
50+
module bool
51+
service bool
52+
route bool
5353
}
5454

5555
// Module specifies the module label for RequestDurationSeconds.
5656
func (r *RequestDurationSeconds) Module(module string) *RequestDurationSeconds {
5757
return &RequestDurationSeconds{
5858
Histogram: r.Histogram.With("module", module),
59-
module: module,
59+
module: true,
6060
service: r.service,
6161
route: r.route,
6262
}
@@ -67,7 +67,7 @@ func (r *RequestDurationSeconds) Service(service string) *RequestDurationSeconds
6767
return &RequestDurationSeconds{
6868
Histogram: r.Histogram.With("service", service),
6969
module: r.module,
70-
service: service,
70+
service: true,
7171
route: r.route,
7272
}
7373
}
@@ -78,11 +78,20 @@ func (r *RequestDurationSeconds) Route(route string) *RequestDurationSeconds {
7878
Histogram: r.Histogram.With("route", route),
7979
module: r.module,
8080
service: r.service,
81-
route: route,
81+
route: true,
8282
}
8383
}
8484

8585
// Observe records the time taken to process the request.
8686
func (r *RequestDurationSeconds) Observe(seconds float64) {
87+
if !r.module {
88+
r.Histogram = r.Histogram.With("module", "")
89+
}
90+
if !r.service {
91+
r.Histogram = r.Histogram.With("service", "")
92+
}
93+
if !r.route {
94+
r.Histogram = r.Histogram.With("route", "")
95+
}
8796
r.Histogram.Observe(seconds)
8897
}

srvhttp/metrics_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,11 @@ func TestRequestDurationSeconds(t *testing.T) {
2727
h.ServeHTTP(nil, httptest.NewRequest(http.MethodGet, "/", nil))
2828
assert.GreaterOrEqual(t, 1.0, rds.Histogram.(*generic.Histogram).Quantile(0.5))
2929
}
30+
31+
func TestRequestDurationSeconds_noPanicWhenMissingLabels(t *testing.T) {
32+
rds := &RequestDurationSeconds{
33+
Histogram: generic.NewHistogram("foo", 2),
34+
}
35+
rds.Observe(50)
36+
assert.ElementsMatch(t, []string{"module", "", "service", "", "route", ""}, rds.Histogram.(*generic.Histogram).LabelValues())
37+
}

0 commit comments

Comments
 (0)