Skip to content

feat: add path & method labels to prometheus metrics for current requests #17362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 16, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
added path matching to prometheus middleware
  • Loading branch information
ibetitsmike committed Apr 15, 2025
commit 3ff76bb26313611cf7b5ee417d3c2fc131f22bcc
27 changes: 25 additions & 2 deletions coderd/httpmw/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ func Prometheus(register prometheus.Registerer) func(http.Handler) http.Handler
var (
start = time.Now()
method = r.Method
rctx = chi.RouteContext(r.Context())
// rctx = chi.RouteContext(r.Context())
)

sw, ok := w.(*tracing.StatusWriter)
if !ok {
panic("dev error: http.ResponseWriter is not *tracing.StatusWriter")
}

path := rctx.RoutePattern()
path := getRoutePattern(r)

var (
dist *prometheus.HistogramVec
Expand Down Expand Up @@ -99,3 +99,26 @@ func Prometheus(register prometheus.Registerer) func(http.Handler) http.Handler
})
}
}

func getRoutePattern(r *http.Request) string {
rctx := chi.RouteContext(r.Context())
if pattern := rctx.RoutePattern(); pattern != "" {
// Pattern is already available
return pattern
}

routePath := r.URL.Path
if r.URL.RawPath != "" {
routePath = r.URL.RawPath
}

tctx := chi.NewRouteContext()
if !rctx.Routes.Match(tctx, r.Method, routePath) {
// No matching pattern, so just return an empty string.
// It is done to avoid returning a static path for frontend requests.
return ""
}

// tctx has the updated pattern, since Match mutates it
return tctx.RoutePattern()
}