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