Debian Codegraph @

instrumentation/google.golang.org/grpc/otelgrpc/example_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelgrpc_test
5
6 import (
7 "context"
8
9 "go.opentelemetry.io/otel/attribute"
10 "go.opentelemetry.io/otel/baggage"
11 "go.opentelemetry.io/otel/propagation"
12 "google.golang.org/grpc"
13 "google.golang.org/grpc/metadata"
14
15 "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
16 )
17
18 func ExampleNewClientHandler() {
19 _, _ = grpc.NewClient("localhost", grpc.WithStatsHandler(otelgrpc.NewClientHandler()))
20 }
21
22 func ExampleNewServerHandler() {
23 _ = grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler()))
24 }
25
26 // ExampleNewClientHandler_withMetricAttributesFn_interceptor demonstrates how to add a dynamic
27 // client-side attribute using gRPC interceptors to the auto-instrumented metrics.
28 func ExampleNewClientHandler_withMetricAttributesFn_interceptor() {
29 // should be centralized, example only
30 type retryAttemptKey struct{}
31
32 // a gRPC client interceptor must populate that key with the actual retry attempt, e.g.,
33 // ...
34 // interceptor := func(ctx context.Context, method string, req, reply any,
35 // cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
36 // ...
37 // ctx = context.WithValue(ctx, retryAttemptKey{}, attempt)
38 // return invoker(ctx, method, req, reply, cc, opts...)
39 // }
40 // ...
41
42 _, _ = grpc.NewClient("localhost", grpc.WithStatsHandler(otelgrpc.NewClientHandler(
43 otelgrpc.WithMetricAttributesFn(func(ctx context.Context) []attribute.KeyValue {
44 if attempt, ok := ctx.Value(retryAttemptKey{}).(int); ok {
45 return []attribute.KeyValue{
46 // Caution: example only.
47 // This must be a controlled, bounded and very limited set of numbers
48 // so that you don't end up with very high cardinality.
49 attribute.Int("retry.attempt", attempt),
50 }
51 }
52
53 return nil
54 }),
55 )))
56 }
57
58 // ExampleNewClientHandler_withMetricAttributesFn_baggage demonstrates how to add a dynamic
59 // client-side attribute using W3C baggage to the auto-instrumented metrics.
60 func ExampleNewClientHandler_withMetricAttributesFn_baggage() {
61 // Baggage must be set in the context before making the call, e.g.,
62 // ...
63 // member, err := baggage.NewMember("traffic.type", "internal")
64 // ...
65 // bag, err := baggage.New(member)
66 // ...
67 // ctx := baggage.ContextWithBaggage(ctx, bag)
68 // ...
69
70 _, _ = grpc.NewClient("localhost", grpc.WithStatsHandler(otelgrpc.NewClientHandler(
71 otelgrpc.WithMetricAttributesFn(func(ctx context.Context) []attribute.KeyValue {
72 bag := baggage.FromContext(ctx)
73 if trafficType := bag.Member("traffic.type"); trafficType.Value() != "" {
74 return []attribute.KeyValue{
75 attribute.String("traffic.type", trafficType.Value()),
76 }
77 }
78
79 return nil
80 }),
81 )))
82 }
83
84 // ExampleNewServerHandler_withMetricAttributesFn_metadata demonstrates how to add a dynamic
85 // server-side attribute using gRPC metadata to the auto-instrumented metrics.
86 func ExampleNewServerHandler_withMetricAttributesFn_metadata() {
87 // The client must set metadata in the outgoing context beforehand, e.g.,
88 // ...
89 // ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("origin", "some-origin"))
90 // ...
91 _ = grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler(
92 otelgrpc.WithMetricAttributesFn(func(ctx context.Context) []attribute.KeyValue {
93 md, ok := metadata.FromIncomingContext(ctx)
94 if ok {
95 if origins := md.Get("origin"); len(origins) > 0 && origins[0] != "" {
96 return []attribute.KeyValue{attribute.String("origin", origins[0])}
97 }
98 }
99
100 // Some use-cases might require to fallback to a default.
101 return []attribute.KeyValue{attribute.String("origin", "unknown")}
102 }),
103 )))
104 }
105
106 // ExampleNewServerHandler_withMetricAttributesFn_baggage demonstrates how to add a dynamic
107 // server-side attribute using W3C baggage to the auto-instrumented metrics.
108 func ExampleNewServerHandler_withMetricAttributesFn_baggage() {
109 // The client must set baggage in context beforehand and have baggage propagators configured to
110 // inject it into the headers (see https://pkg.go.dev/go.opentelemetry.io/otel/propagation#section-documentation), e.g.,
111 //
112 // conn, err := grpc.NewClient(
113 // ...
114 // grpc.WithStatsHandler(otelgrpc.NewClientHandler(
115 // otelgrpc.WithPropagators(propagation.NewCompositeTextMapPropagator(
116 // propagation.Baggage{},
117 // )),
118 // )),
119 //)
120 // ...
121 // member, err := baggage.NewMember("tenant.tier", "premium")
122 // ...
123 // bag, err := baggage.New(member)
124 // ...
125 // ctx := baggage.ContextWithBaggage(ctx, bag)
126 // ...
127
128 _ = grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler(
129 // Propagators are required to extract baggage from incoming request headers.
130 otelgrpc.WithPropagators(propagation.NewCompositeTextMapPropagator(
131 propagation.TraceContext{},
132 propagation.Baggage{},
133 )),
134 otelgrpc.WithMetricAttributesFn(func(ctx context.Context) []attribute.KeyValue {
135 bag := baggage.FromContext(ctx)
136 if tier := bag.Member("tenant.tier"); tier.Value() != "" {
137 return []attribute.KeyValue{
138 attribute.String("tenant.tier", tier.Value()),
139 }
140 }
141
142 return nil
143 }),
144 )))
145 }