Skip to content

Commit

Permalink
metrics: dont create new api_request_latencies_* for 404s
Browse files Browse the repository at this point in the history
  • Loading branch information
vitrvvivs committed May 18, 2024
1 parent c596cdc commit e1b1b8f
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 12 deletions.
1 change: 1 addition & 0 deletions .changelog/692.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
metrics: dont create new 'api_request_latencies_buckets' for 404s
10 changes: 1 addition & 9 deletions api/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ func MetricsMiddleware(m metrics.RequestMetrics, logger log.Logger) func(next ht
)
t := time.Now()
metricName := normalizeEndpoint(r.URL.Path)
timer := m.RequestLatencies(metricName)

// Serve the request.
next.ServeHTTP(w, r.WithContext(
Expand All @@ -74,14 +73,6 @@ func MetricsMiddleware(m metrics.RequestMetrics, logger log.Logger) func(next ht

// Observe results and log/record them.
httpStatus := reflect.ValueOf(w).Elem().FieldByName("status").Int()
if httpStatus < 400 || httpStatus >= 500 {
// Only observe the request timing if it's not going to be
// ignored (see below).
// Timers are reported to Prometheus only after they're
// observed, so it's OK to create it above and then ignore it
// like we're doing here if we don't want to use it.
timer.ObserveDuration()
}
latency := time.Since(t)
logger.Info("ending request",
"query_path", r.URL.Path,
Expand All @@ -103,6 +94,7 @@ func MetricsMiddleware(m metrics.RequestMetrics, logger log.Logger) func(next ht
metricName = "ignored"
}
m.RequestCounts(metricName, statusTxt).Inc()
m.RequestLatencies(metricName).Observe(latency.Seconds())
})
}
}
Expand Down
8 changes: 5 additions & 3 deletions metrics/requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ func (m *RequestMetrics) RequestCounts(endpoint, status string) prometheus.Count
return m.requestCounts.WithLabelValues(endpoint, status)
}

// RequestLatencies creates a new latency timer for the provided request endpoint.
func (m *RequestMetrics) RequestLatencies(endpoint string) *prometheus.Timer {
return prometheus.NewTimer(m.requestLatencies.WithLabelValues(endpoint))
// RequestLatencies fetches the Histogram Observer for the given endpoint
// If it doesn't exist, a new one is created.
// This creates 12 (with DefBuckets) empty tables in the prometheus database.
func (m *RequestMetrics) RequestLatencies(endpoint string) prometheus.Observer {
return m.requestLatencies.WithLabelValues(endpoint)
}

0 comments on commit e1b1b8f

Please sign in to comment.