prometheusinterceptor.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "strconv"
  5. "github.com/zeromicro/go-zero/core/metric"
  6. "github.com/zeromicro/go-zero/core/timex"
  7. "google.golang.org/grpc"
  8. "google.golang.org/grpc/status"
  9. )
  10. const serverNamespace = "rpc_server"
  11. var (
  12. metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  13. Namespace: serverNamespace,
  14. Subsystem: "requests",
  15. Name: "duration_ms",
  16. Help: "rpc server requests duration(ms).",
  17. Labels: []string{"method"},
  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: "rpc server requests code count.",
  25. Labels: []string{"method", "code"},
  26. })
  27. )
  28. // UnaryPrometheusInterceptor reports the statistics to the prometheus server.
  29. func UnaryPrometheusInterceptor(ctx context.Context, req any,
  30. info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
  31. startTime := timex.Now()
  32. resp, err := handler(ctx, req)
  33. metricServerReqDur.Observe(timex.Since(startTime).Milliseconds(), info.FullMethod)
  34. metricServerReqCodeTotal.Inc(info.FullMethod, strconv.Itoa(int(status.Code(err))))
  35. return resp, err
  36. }