Debian Codegraph @

sdk/trace/span_processor_annotator_example_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package trace
5
6 import (
7 "context"
8 "fmt"
9
10 "go.opentelemetry.io/otel/attribute"
11 )
12
13 /*
14 Sometimes information about a runtime environment can change dynamically or be
15 delayed from startup. Instead of continuously recreating and distributing a
16 TracerProvider with an immutable Resource or delaying the startup of your
17 application on a slow-loading piece of information, annotate the created spans
18 dynamically using a SpanProcessor.
19 */
20
21 var (
22 // owner represents the owner of the application. In this example it is
23 // stored as a simple string, but in real-world use this may be the
24 // response to an asynchronous request.
25 owner = "unknown"
26 ownerKey = attribute.Key("owner")
27 )
28
29 // Annotator is a SpanProcessor that adds attributes to all started spans.
30 type Annotator struct {
31 // AttrsFunc is called when a span is started. The attributes it returns
32 // are set on the Span being started.
33 AttrsFunc func() []attribute.KeyValue
34 }
35
36 func (a Annotator) OnStart(_ context.Context, s ReadWriteSpan) { s.SetAttributes(a.AttrsFunc()...) }
37 func (Annotator) Shutdown(context.Context) error { return nil }
38 func (Annotator) ForceFlush(context.Context) error { return nil }
39 func (Annotator) OnEnd(s ReadOnlySpan) {
40 attr := s.Attributes()[0]
41 fmt.Printf("%s: %s\n", attr.Key, attr.Value.AsString())
42 }
43
44 func ExampleSpanProcessor_annotated() {
45 a := Annotator{
46 AttrsFunc: func() []attribute.KeyValue {
47 return []attribute.KeyValue{ownerKey.String(owner)}
48 },
49 }
50 tracer := NewTracerProvider(WithSpanProcessor(a)).Tracer("annotated")
51
52 // Simulate the situation where we want to annotate spans with an owner,
53 // but at startup we do not now this information. Instead of waiting for
54 // the owner to be known before starting and blocking here, start doing
55 // work and update when the information becomes available.
56 ctx := context.Background()
57 _, s0 := tracer.Start(ctx, "span0")
58
59 // Simulate an asynchronous call to determine the owner succeeding. We now
60 // know that the owner of this application has been determined to be
61 // Alice. Make sure all subsequent spans are annotated appropriately.
62 owner = "alice"
63
64 _, s1 := tracer.Start(ctx, "span1")
65 s0.End()
66 s1.End()
67
68 // Output:
69 // owner: unknown
70 // owner: alice
71 }