prometheusinterceptor.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package clientinterceptors
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "github.com/tal-tech/go-zero/core/metric"
  7. "github.com/tal-tech/go-zero/core/timex"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/status"
  10. )
  11. const clientNamespace = "rpc_client"
  12. var (
  13. metricClientReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  14. Namespace: clientNamespace,
  15. Subsystem: "requests",
  16. Name: "duration_ms",
  17. Help: "rpc client requests duration(ms).",
  18. Labels: []string{"method"},
  19. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  20. })
  21. metricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  22. Namespace: clientNamespace,
  23. Subsystem: "requests",
  24. Name: "code_total",
  25. Help: "rpc client requests code count.",
  26. Labels: []string{"method", "code"},
  27. })
  28. )
  29. func PrometheusInterceptor(ctx context.Context, method string, req, reply interface{},
  30. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  31. startTime := timex.Now()
  32. err := invoker(ctx, method, req, reply, cc, opts...)
  33. metricClientReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), method)
  34. metricClientReqCodeTotal.Inc(method, strconv.Itoa(int(status.Code(err))))
  35. return err
  36. }