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