@@ -30,6 +30,16 @@ type gRPCContext struct {
3030 record bool
3131}
3232
33+ // AddAttrs adds attributes to the given context.
34+ func AddAttrs (ctx context.Context , attrs ... attribute.KeyValue ) context.Context {
35+ gctx , ok := ctx .Value (gRPCContextKey {}).(* gRPCContext )
36+ if ! ok {
37+ gctx = & gRPCContext {}
38+ }
39+ gctx .metricAttrs = append (gctx .metricAttrs , attrs ... )
40+ return context .WithValue (ctx , gRPCContextKey {}, gctx )
41+ }
42+
3343type serverHandler struct {
3444 * config
3545}
@@ -58,17 +68,21 @@ func (h *serverHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) cont
5868
5969 name , attrs := internal .ParseFullMethod (info .FullMethodName )
6070 attrs = append (attrs , RPCSystemGRPC )
71+
72+ gctx , ok := ctx .Value (gRPCContextKey {}).(* gRPCContext )
73+ if ! ok {
74+ gctx = & gRPCContext {}
75+ }
76+ gctx .metricAttrs = append (gctx .metricAttrs , attrs ... )
77+
6178 ctx , _ = h .tracer .Start (
6279 trace .ContextWithRemoteSpanContext (ctx , trace .SpanContextFromContext (ctx )),
6380 name ,
6481 trace .WithSpanKind (trace .SpanKindServer ),
65- trace .WithAttributes (attrs ... ),
82+ trace .WithAttributes (gctx . metricAttrs ... ),
6683 )
6784
68- gctx := gRPCContext {
69- metricAttrs : attrs ,
70- record : true ,
71- }
85+ gctx .record = true
7286 if h .config .Filter != nil {
7387 gctx .record = h .config .Filter (info )
7488 }
@@ -98,17 +112,21 @@ func NewClientHandler(opts ...Option) stats.Handler {
98112func (h * clientHandler ) TagRPC (ctx context.Context , info * stats.RPCTagInfo ) context.Context {
99113 name , attrs := internal .ParseFullMethod (info .FullMethodName )
100114 attrs = append (attrs , RPCSystemGRPC )
115+
116+ gctx , ok := ctx .Value (gRPCContextKey {}).(* gRPCContext )
117+ if ! ok {
118+ gctx = & gRPCContext {}
119+ }
120+ gctx .metricAttrs = append (gctx .metricAttrs , attrs ... )
121+
101122 ctx , _ = h .tracer .Start (
102123 ctx ,
103124 name ,
104125 trace .WithSpanKind (trace .SpanKindClient ),
105- trace .WithAttributes (attrs ... ),
126+ trace .WithAttributes (gctx . metricAttrs ... ),
106127 )
107128
108- gctx := gRPCContext {
109- metricAttrs : attrs ,
110- record : true ,
111- }
129+ gctx .record = true
112130 if h .config .Filter != nil {
113131 gctx .record = h .config .Filter (info )
114132 }
0 commit comments