prometheusinterceptor.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "git.i2edu.net/i2/go-zero/core/metric"
  7. "git.i2edu.net/i2/go-zero/core/prometheus"
  8. "git.i2edu.net/i2/go-zero/core/timex"
  9. "google.golang.org/grpc"
  10. "google.golang.org/grpc/status"
  11. )
  12. const serverNamespace = "rpc_server"
  13. var (
  14. metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  15. Namespace: serverNamespace,
  16. Subsystem: "requests",
  17. Name: "duration_ms",
  18. Help: "rpc server requests duration(ms).",
  19. Labels: []string{"method"},
  20. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  21. })
  22. metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  23. Namespace: serverNamespace,
  24. Subsystem: "requests",
  25. Name: "code_total",
  26. Help: "rpc server requests code count.",
  27. Labels: []string{"method", "code"},
  28. })
  29. )
  30. // UnaryPrometheusInterceptor returns a func that reports to the prometheus server.
  31. func UnaryPrometheusInterceptor() grpc.UnaryServerInterceptor {
  32. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (
  33. interface{}, error) {
  34. if !prometheus.Enabled() {
  35. return handler(ctx, req)
  36. }
  37. startTime := timex.Now()
  38. resp, err := handler(ctx, req)
  39. metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), info.FullMethod)
  40. metricServerReqCodeTotal.Inc(info.FullMethod, strconv.Itoa(int(status.Code(err))))
  41. return resp, err
  42. }
  43. }