Skip to content

Commit

Permalink
fix(srvhttp): RequestDurationSeconds shouldn't panic when missing lab…
Browse files Browse the repository at this point in the history
…els (#207)
  • Loading branch information
Reasno authored Oct 21, 2021
1 parent ab0fffc commit e72a19d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
23 changes: 16 additions & 7 deletions srvhttp/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -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,
}
}
Expand All @@ -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)
}
8 changes: 8 additions & 0 deletions srvhttp/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

0 comments on commit e72a19d

Please sign in to comment.