当我收到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
}
}发布于 2022-11-26 23:03:49
在TagRPC的实现中,可以创建一个结构并添加指向上下文的指针。然后在对HandleRPC的连续调用中添加信息。因此,如果您需要有效负载中只有*stats.InPayload调用中可用的内容,可以将其提取出来并存储在添加到上下文的结构中,然后在HandleRPC再次被*stats.End调用时访问它
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 #
}
}https://stackoverflow.com/questions/72673612
复制相似问题