prometheushandler.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package handler
  2. import (
  3. "net/http"
  4. "strconv"
  5. "time"
  6. "github.com/tal-tech/go-zero/core/metric"
  7. "github.com/tal-tech/go-zero/core/timex"
  8. "github.com/tal-tech/go-zero/rest/internal/security"
  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. func PromethousHandler(path 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 := &security.WithCodeResponseWriter{Writer: w}
  33. defer func() {
  34. metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), path)
  35. metricServerReqCodeTotal.Inc(path, strconv.Itoa(cw.Code))
  36. }()
  37. next.ServeHTTP(cw, r)
  38. })
  39. }
  40. }