github.com/shuguocloud/go-zero@v1.3.0/zrpc/internal/clientinterceptors/prometheusinterceptor.go (about) 1 package clientinterceptors 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 clientNamespace = "rpc_client" 16 17 var ( 18 metricClientReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{ 19 Namespace: clientNamespace, 20 Subsystem: "requests", 21 Name: "duration_ms", 22 Help: "rpc client requests duration(ms).", 23 Labels: []string{"method"}, 24 Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000}, 25 }) 26 27 metricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{ 28 Namespace: clientNamespace, 29 Subsystem: "requests", 30 Name: "code_total", 31 Help: "rpc client requests code count.", 32 Labels: []string{"method", "code"}, 33 }) 34 ) 35 36 // PrometheusInterceptor is an interceptor that reports to prometheus server. 37 func PrometheusInterceptor(ctx context.Context, method string, req, reply interface{}, 38 cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { 39 if !prometheus.Enabled() { 40 return invoker(ctx, method, req, reply, cc, opts...) 41 } 42 43 startTime := timex.Now() 44 err := invoker(ctx, method, req, reply, cc, opts...) 45 metricClientReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), method) 46 metricClientReqCodeTotal.Inc(method, strconv.Itoa(int(status.Code(err)))) 47 return err 48 }