prometheushandler.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package handler
  2. import (
  3. "net/http"
  4. "strconv"
  5. "time"
  6. "github.com/zeromicro/go-zero/core/metric"
  7. "github.com/zeromicro/go-zero/core/timex"
  8. "github.com/zeromicro/go-zero/rest/internal/response"
  9. )
  10. const serverNamespace = "http_server"
  11. var (
  12. metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  13. Namespace: serverNamespace,
  14. Subsystem: "requests",
  15. Name: "duration_ms",
  16. Help: "http server requests duration(ms).",
  17. Labels: []string{"path"},
  18. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  19. })
  20. metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  21. Namespace: serverNamespace,
  22. Subsystem: "requests",
  23. Name: "code_total",
  24. Help: "http server requests error count.",
  25. Labels: []string{"path", "code"},
  26. })
  27. )
  28. // PrometheusHandler returns a middleware that reports stats to prometheus.
  29. func PrometheusHandler(path string) func(http.Handler) http.Handler {
  30. return func(next http.Handler) http.Handler {
  31. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. startTime := timex.Now()
  33. cw := &response.WithCodeResponseWriter{Writer: w}
  34. defer func() {
  35. metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), path)
  36. metricServerReqCodeTotal.Inc(path, strconv.Itoa(cw.Code))
  37. }()
  38. next.ServeHTTP(cw, r)
  39. })
  40. }
  41. }