go-zero/zrpc/internal/clientinterceptors/prometheusinterceptor.go

44 lines
1.3 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package clientinterceptors
import (
"context"
"strconv"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/metric"
"github.com/tal-tech/go-zero/core/timex"
2020-07-26 17:09:05 +08:00
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
const clientNamespace = "rpc_client"
var (
metricClientReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
Namespace: clientNamespace,
Subsystem: "requests",
Name: "duration_ms",
Help: "rpc client requests duration(ms).",
Labels: []string{"method"},
Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
})
metricClientReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: clientNamespace,
Subsystem: "requests",
Name: "code_total",
Help: "rpc client requests code count.",
Labels: []string{"method", "code"},
})
)
2021-03-01 23:52:44 +08:00
// PrometheusInterceptor is an interceptor that reports to prometheus server.
2020-09-27 17:15:15 +08:00
func PrometheusInterceptor(ctx context.Context, method string, req, reply interface{},
2020-07-26 17:09:05 +08:00
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
startTime := timex.Now()
err := invoker(ctx, method, req, reply, cc, opts...)
metricClientReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), method)
metricClientReqCodeTotal.Inc(method, strconv.Itoa(int(status.Code(err))))
return err
}