prometheushandler.go 1.4 KB

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