prometheusinterceptor.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // PrometheusInterceptor is an interceptor that reports to prometheus server.
  30. func PrometheusInterceptor(ctx context.Context, method string, req, reply interface{},
  31. cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  32. startTime := timex.Now()
  33. err := invoker(ctx, method, req, reply, cc, opts...)
  34. metricClientReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), method)
  35. metricClientReqCodeTotal.Inc(method, strconv.Itoa(int(status.Code(err))))
  36. return err
  37. }