prometheusinterceptor.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package serverinterceptors
  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 serverNamespace = "rpc_server"
  12. var (
  13. metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  14. Namespace: serverNamespace,
  15. Subsystem: "requests",
  16. Name: "duration_ms",
  17. Help: "rpc server requests duration(ms).",
  18. Labels: []string{"method"},
  19. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  20. })
  21. metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  22. Namespace: serverNamespace,
  23. Subsystem: "requests",
  24. Name: "code_total",
  25. Help: "rpc server requests code count.",
  26. Labels: []string{"method", "code"},
  27. })
  28. )
  29. // UnaryPrometheusInterceptor returns a func that reports to the prometheus server.
  30. func UnaryPrometheusInterceptor() grpc.UnaryServerInterceptor {
  31. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (
  32. interface{}, error) {
  33. startTime := timex.Now()
  34. resp, err := handler(ctx, req)
  35. metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), info.FullMethod)
  36. metricServerReqCodeTotal.Inc(info.FullMethod, strconv.Itoa(int(status.Code(err))))
  37. return resp, err
  38. }
  39. }