在 grpc-go 的 stat/HandleRPC 中访问有关请求和响应有效负载的信息



当我接收到stats/End数据时,我正在使用stats/HandleRPC()来发出一些关于RPC持续时间的指标,并且我想用一些可以从传入和传出有效负载中提取的信息标记这些指标。实现这一目标的最佳方式是什么?

func (h *myStatsHandler) HandleRPC(ctx context.Context, rpcStats stats.RPCStats) {
switch stat := rpcStats.(type) {
case *stats.End:
durationMs := stat.EndTime.Sub(stat.BeginTime).Seconds() * 1000.0
// Now before sending this value, I need to know, for example the value of a specific key in the request payload, or whether the response is nil or not 
}
}

TagRPC的实现中,您可以创建一个结构体并添加一个指向上下文的指针。然后在对HandleRPC的连续调用中添加信息。因此,如果您需要仅在*stats.InPayload调用中可用的有效负载中的某些内容,则可以将其拉出并将其存储在添加到上下文的结构中,然后在*stats.End再次调用HandleRPC时访问它

type recorderCtxKey struct{}
type recorder struct {
size   int64
}
func (sl *statsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
return context.WithValue(ctx, rpcStatCtxKey{}, &recorder{})
}
func (h *statsHandler) HandleRPC(ctx context.Context, rpcStats stats.RPCStats) {
switch stat := rpcStats.(type) {
case *stats.InPayload:
r, _ := ctx.Value(recorderContextKey{}).(*Recorder)
r.size += stat.WireLength
case *stats.End:
durationMs := stat.EndTime.Sub(stat.BeginTime).Seconds() * 1000.0
r, _ := ctx.Value(recorderContextKey{}).(*Recorder)
# use r.size #
}
}

最新更新