prometheusinterceptor.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. func UnaryPrometheusInterceptor() grpc.UnaryServerInterceptor {
  30. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (
  31. interface{}, error) {
  32. startTime := timex.Now()
  33. resp, err := handler(ctx, req)
  34. metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), info.FullMethod)
  35. metricServerReqCodeTotal.Inc(info.FullMethod, strconv.Itoa(int(status.Code(err))))
  36. return resp, err
  37. }
  38. }