Skip to content

Commit 4f000e0

Browse files
committed
chore: update propagation example with new expected usage
1 parent adb0c13 commit 4f000e0

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

examples/opentelemetry-remote-context.rs

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
1-
use opentelemetry::{global, Context};
1+
use opentelemetry::global;
2+
use opentelemetry::trace::TraceContextExt;
23
use opentelemetry_sdk::propagation::TraceContextPropagator;
34
use std::collections::HashMap;
4-
use tracing::span;
5+
use tracing::{span, Span};
56
use tracing_opentelemetry::OpenTelemetrySpanExt;
67
use tracing_subscriber::layer::SubscriberExt;
78
use tracing_subscriber::Registry;
89

9-
fn make_request(_cx: Context) {
10-
// perform external request after injecting context
11-
// e.g. if there are request headers that impl `opentelemetry::propagation::Injector`
12-
// then `propagator.inject_context(cx, request.headers_mut())`
10+
fn make_request() {
11+
let context = Span::current().context();
12+
13+
assert!(context.span().span_context().is_valid());
14+
15+
// Perform external request after injecting context. See `opentelemetry::propagation` for
16+
// details.
1317
}
1418

1519
fn build_example_carrier() -> HashMap<String, String> {
@@ -37,10 +41,21 @@ fn main() {
3741
let app_root = span!(tracing::Level::INFO, "app_start");
3842

3943
// Assign parent trace from external context
40-
let _ = app_root.set_parent(parent_context);
41-
42-
// To include tracing context in client requests from _this_ app,
43-
// use `context` to extract the current OpenTelemetry context.
44-
make_request(app_root.context());
44+
if let Err(error) = app_root.set_parent(parent_context) {
45+
tracing::error!(
46+
error = debug(error),
47+
"Unable to set OpenTelemetry parent, span relationships will be wrong!"
48+
);
49+
// You don't want to panic in this case in production environment. Instead, you can log
50+
// this to know your traces may have wrong relationships but let the business logic
51+
// continue.
52+
panic!("Could not set parent.");
53+
}
54+
55+
app_root.in_scope(|| {
56+
// The context can be accessed in the `tracing` span. Just make sure that the correct
57+
// `tracing` span is entered and the propagating library should be able to handle it.
58+
make_request();
59+
});
4560
});
4661
}

0 commit comments

Comments
 (0)