metricsinterceptor.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package internal
  2. import (
  3. "net/http"
  4. "net/url"
  5. "strconv"
  6. "time"
  7. "github.com/wuntsong-org/go-zero-plus/core/metric"
  8. "github.com/wuntsong-org/go-zero-plus/core/timex"
  9. )
  10. const clientNamespace = "httpc_client"
  11. var (
  12. MetricClientReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  13. Namespace: clientNamespace,
  14. Subsystem: "requests",
  15. Name: "duration_ms",
  16. Help: "http client requests duration(ms).",
  17. Labels: []string{"name", "method", "url"},
  18. Buckets: []float64{0.25, 0.5, 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2000, 5000, 10000, 15000},
  19. })
  20. MetricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  21. Namespace: clientNamespace,
  22. Subsystem: "requests",
  23. Name: "code_total",
  24. Help: "http client requests code count.",
  25. Labels: []string{"name", "method", "url", "code"},
  26. })
  27. )
  28. type MetricsURLRewriter func(u url.URL) string
  29. func MetricsInterceptor(name string, pr MetricsURLRewriter) Interceptor {
  30. return func(r *http.Request) (*http.Request, ResponseHandler) {
  31. startTime := timex.Now()
  32. return r, func(resp *http.Response, err error) {
  33. var code int
  34. var path string
  35. // error or resp is nil, set code=500
  36. if err != nil || resp == nil {
  37. code = http.StatusInternalServerError
  38. } else {
  39. code = resp.StatusCode
  40. }
  41. u := cleanURL(*r.URL)
  42. method := r.Method
  43. if pr != nil {
  44. path = pr(u)
  45. } else {
  46. path = u.String()
  47. }
  48. MetricClientReqDur.ObserveFloat(float64(timex.Since(startTime))/float64(time.Millisecond), name, method, path)
  49. MetricClientReqCodeTotal.Inc(name, method, path, strconv.Itoa(code))
  50. }
  51. }
  52. }
  53. func cleanURL(r url.URL) url.URL {
  54. r.RawQuery = ""
  55. r.RawFragment = ""
  56. r.User = nil
  57. return r
  58. }