prometheusinterceptor.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package clientinterceptors
  2. import (
  3. "context"
  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. "google.golang.org/grpc"
  10. "google.golang.org/grpc/status"
  11. )
  12. const clientNamespace = "rpc_client"
  13. var (
  14. metricClientReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  15. Namespace: clientNamespace,
  16. Subsystem: "requests",
  17. Name: "duration_ms",
  18. Help: "rpc client requests duration(ms).",
  19. Labels: []string{"method"},
  20. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  21. })
  22. metricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  23. Namespace: clientNamespace,
  24. Subsystem: "requests",
  25. Name: "code_total",
  26. Help: "rpc client requests code count.",
  27. Labels: []string{"method", "code"},
  28. })
  29. )
  30. // PrometheusInterceptor is an interceptor that reports to prometheus server.
  31. func PrometheusInterceptor(ctx context.Context, method string, req, reply interface{},
  32. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  33. if !prometheus.Enabled() {
  34. return invoker(ctx, method, req, reply, cc, opts...)
  35. }
  36. startTime := timex.Now()
  37. err := invoker(ctx, method, req, reply, cc, opts...)
  38. metricClientReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), method)
  39. metricClientReqCodeTotal.Inc(method, strconv.Itoa(int(status.Code(err))))
  40. return err
  41. }