You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/rest/handler/prometheushandler.go

49 lines
1.4 KiB
Go

4 years ago
package handler
4 years ago
import (
"net/http"
"strconv"
"github.com/zeromicro/go-zero/core/metric"
"github.com/zeromicro/go-zero/core/timex"
"github.com/zeromicro/go-zero/rest/internal/response"
4 years ago
)
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", "method", "code"},
Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 750, 1000},
4 years ago
})
metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "code_total",
Help: "http server requests error count.",
Labels: []string{"path", "method", "code"},
4 years ago
})
)
// PrometheusHandler returns a middleware that reports stats to prometheus.
func PrometheusHandler(path, method string) func(http.Handler) http.Handler {
4 years ago
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := timex.Now()
cw := response.NewWithCodeResponseWriter(w)
4 years ago
defer func() {
code := strconv.Itoa(cw.Code)
metricServerReqDur.Observe(timex.Since(startTime).Milliseconds(), path, method, code)
metricServerReqCodeTotal.Inc(path, method, code)
4 years ago
}()
next.ServeHTTP(cw, r)
})
}
}