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

46 lines
1.3 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package serverinterceptors
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 serverNamespace = "rpc_server"
var (
metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "duration_ms",
Help: "rpc server requests duration(ms).",
Labels: []string{"method"},
Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
})
metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "code_total",
Help: "rpc server requests code count.",
Labels: []string{"method", "code"},
})
)
2021-03-01 23:52:44 +08:00
// UnaryPrometheusInterceptor returns a func that reports to the prometheus server.
2020-09-27 17:15:15 +08:00
func UnaryPrometheusInterceptor() grpc.UnaryServerInterceptor {
2020-08-20 22:53:18 +08:00
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (
interface{}, error) {
2020-07-26 17:09:05 +08:00
startTime := timex.Now()
resp, err := handler(ctx, req)
metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), info.FullMethod)
metricServerReqCodeTotal.Inc(info.FullMethod, strconv.Itoa(int(status.Code(err))))
return resp, err
}
}