Debian Codegraph @

propagators/envcar/carrier_example_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package envcar_test
5
6 import (
7 "context"
8 "fmt"
9 "os"
10 "os/exec"
11
12 "go.opentelemetry.io/otel/propagation"
13 "go.opentelemetry.io/otel/trace"
14
15 "go.opentelemetry.io/contrib/propagators/envcar"
16 )
17
18 // This example is a go program where the environment variables are carrying the
19 // trace information, and we're going to pick them up into our context.
20 func ExampleCarrier_extractFromParent() {
21 // Simulate environment variables set by a parent process.
22 // In practice, these would already be set when this process starts.
23 _ = os.Setenv("TRACEPARENT", "00-0102030405060708090a0b0c0d0e0f10-0102030405060708-01")
24
25 // Create a carrier to read trace context from environment variables.
26 carrier := envcar.Carrier{}
27
28 // Extract trace context that was propagated by the parent process.
29 prop := propagation.TraceContext{}
30 ctx := prop.Extract(context.Background(), &carrier)
31
32 // The context now contains the span context from the parent.
33 spanCtx := trace.SpanContextFromContext(ctx)
34 fmt.Printf("Trace ID: %s\n", spanCtx.TraceID())
35 fmt.Printf("Span ID: %s\n", spanCtx.SpanID())
36 fmt.Printf("Sampled: %t\n", spanCtx.IsSampled())
37 // Output:
38 // Trace ID: 0102030405060708090a0b0c0d0e0f10
39 // Span ID: 0102030405060708
40 // Sampled: true
41 }
42
43 // This example is a go program where we have a trace and we'd like to inject it
44 // into a command we're going to run.
45 func ExampleCarrier_childProcess() {
46 // Create a span context with a known trace ID.
47 traceID := trace.TraceID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}
48 spanID := trace.SpanID{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}
49 spanCtx := trace.NewSpanContext(trace.SpanContextConfig{
50 TraceID: traceID,
51 SpanID: spanID,
52 TraceFlags: trace.FlagsSampled,
53 })
54 ctx := trace.ContextWithSpanContext(context.Background(), spanCtx)
55
56 // Prepare a command that prints the TRACEPARENT environment variable.
57 cmd := exec.CommandContext(context.Background(), "printenv", "TRACEPARENT")
58 cmd.Env = os.Environ()
59
60 // Create a carrier that injects trace context into the child
61 // process's environment rather than the current process's.
62 carrier := envcar.Carrier{
63 SetEnvFunc: func(key, value string) {
64 cmd.Env = append(cmd.Env, key+"="+value)
65 },
66 }
67
68 // Inject trace context into the child's environment.
69 prop := propagation.TraceContext{}
70 prop.Inject(ctx, &carrier)
71
72 // The child process now has trace context in its environment,
73 // independent of the parent process's environment variables.
74 out, err := cmd.Output()
75 if err != nil {
76 fmt.Println("error:", err)
77 return
78 }
79 fmt.Print(string(out))
80 // Output: 00-0102030405060708090a0b0c0d0e0f10-0102030405060708-01
81 }