aboutsummaryrefslogtreecommitdiffhomepage
path: root/metrics.go
diff options
context:
space:
mode:
authorDave Henderson <[email protected]>2020-09-22 22:10:34 -0400
committerGitHub <[email protected]>2020-09-22 20:10:34 -0600
commitf197cec7f3a599ca18807e7b7719ef7666cfdb70 (patch)
tree59561ce5893b6a9a6ef972285507e6c79dde42b6 /metrics.go
parentbe6daa5fd46edc9f66a5129347482b38e22bf103 (diff)
downloadcaddy-f197cec7f3a599ca18807e7b7719ef7666cfdb70.tar.gz
caddy-f197cec7f3a599ca18807e7b7719ef7666cfdb70.zip
metrics: Always track method label in uppercase (#3742)v2.2.0
* metrics: Always track method label in uppercase Signed-off-by: Dave Henderson <[email protected]> * Just use strings.ToUpper for clarity Signed-off-by: Dave Henderson <[email protected]>
Diffstat (limited to 'metrics.go')
-rw-r--r--metrics.go45
1 files changed, 45 insertions, 0 deletions
diff --git a/metrics.go b/metrics.go
index a7ff3b71d..55fb0a310 100644
--- a/metrics.go
+++ b/metrics.go
@@ -1,6 +1,10 @@
package caddy
import (
+ "net/http"
+ "strconv"
+ "strings"
+
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
@@ -30,3 +34,44 @@ var adminMetrics = struct {
requestCount *prometheus.CounterVec
requestErrors *prometheus.CounterVec
}{}
+
+// Similar to promhttp.InstrumentHandlerCounter, but upper-cases method names
+// instead of lower-casing them.
+//
+// Unlike promhttp.InstrumentHandlerCounter, this assumes a "code" and "method"
+// label is present, and will panic otherwise.
+func instrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ d := newDelegator(w)
+ next.ServeHTTP(d, r)
+ counter.With(prometheus.Labels{
+ "code": sanitizeCode(d.status),
+ "method": strings.ToUpper(r.Method),
+ }).Inc()
+ })
+}
+
+func newDelegator(w http.ResponseWriter) *delegator {
+ return &delegator{
+ ResponseWriter: w,
+ }
+}
+
+type delegator struct {
+ http.ResponseWriter
+ status int
+}
+
+func (d *delegator) WriteHeader(code int) {
+ d.status = code
+ d.ResponseWriter.WriteHeader(code)
+}
+
+func sanitizeCode(s int) string {
+ switch s {
+ case 0, 200:
+ return "200"
+ default:
+ return strconv.Itoa(s)
+ }
+}