prometheushandler.go 1.4 KB

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