go-zero/rest/handler/prometheushandler.go

49 lines
1.3 KiB
Go
Raw Normal View History

2020-07-29 18:00:04 +08:00
package handler
2020-07-26 17:09:05 +08:00
import (
"net/http"
"strconv"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/metric"
"github.com/tal-tech/go-zero/core/timex"
"github.com/tal-tech/go-zero/rest/internal/security"
2020-07-26 17:09:05 +08:00
)
const serverNamespace = "http_server"
var (
metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "duration_ms",
Help: "http server requests duration(ms).",
Labels: []string{"path"},
Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
})
metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "code_total",
Help: "http server requests error count.",
Labels: []string{"path", "code"},
})
)
2021-03-01 19:15:35 +08:00
// PrometheusHandler returns a middleware that reports stats to prometheus.
func PrometheusHandler(path string) func(http.Handler) http.Handler {
2020-07-26 17:09:05 +08:00
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := timex.Now()
2020-07-29 18:00:04 +08:00
cw := &security.WithCodeResponseWriter{Writer: w}
2020-07-26 17:09:05 +08:00
defer func() {
metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), path)
metricServerReqCodeTotal.Inc(path, strconv.Itoa(cw.Code))
}()
next.ServeHTTP(cw, r)
})
}
}