-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
track response time for http endpoints (#1412)
* track response time for http endpoints
- Loading branch information
1 parent
818feff
commit 1ef9fb8
Showing
3 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Copyright 2024 Canonical. | ||
|
||
package middleware | ||
|
||
import ( | ||
"net/http" | ||
"strconv" | ||
"time" | ||
|
||
"github.com/go-chi/chi/v5" | ||
|
||
"github.com/canonical/jimm/v3/internal/servermon" | ||
) | ||
|
||
// statusRecorder to record the status code from the ResponseWriter | ||
type statusRecorder struct { | ||
http.ResponseWriter | ||
statusCode int | ||
} | ||
|
||
func (rec *statusRecorder) WriteHeader(statusCode int) { | ||
rec.statusCode = statusCode | ||
rec.ResponseWriter.WriteHeader(statusCode) | ||
} | ||
|
||
// MeasureHTTPResponseTime tracks response time of HTTP requests. | ||
// We don't track websocket requests. | ||
func MeasureHTTPResponseTime(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
// Check the upgrade header because we only track http endpoints | ||
if r.Header.Get("Upgrade") == "websocket" { | ||
next.ServeHTTP(w, r) | ||
return | ||
} | ||
rec := statusRecorder{w, 200} | ||
start := time.Now() | ||
defer func() { | ||
route := chi.RouteContext(r.Context()).RoutePattern() | ||
statusCode := strconv.Itoa(rec.statusCode) | ||
servermon.ResponseTimeHistogram.WithLabelValues(route, r.Method, statusCode).Observe(time.Since(start).Seconds()) | ||
}() | ||
next.ServeHTTP(&rec, r) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters