|
1 | | -use opentelemetry::{global, Context}; |
| 1 | +use opentelemetry::global; |
| 2 | +use opentelemetry::trace::TraceContextExt; |
2 | 3 | use opentelemetry_sdk::propagation::TraceContextPropagator; |
3 | 4 | use std::collections::HashMap; |
4 | | -use tracing::span; |
| 5 | +use tracing::{span, Span}; |
5 | 6 | use tracing_opentelemetry::OpenTelemetrySpanExt; |
6 | 7 | use tracing_subscriber::layer::SubscriberExt; |
7 | 8 | use tracing_subscriber::Registry; |
8 | 9 |
|
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. |
13 | 17 | } |
14 | 18 |
|
15 | 19 | fn build_example_carrier() -> HashMap<String, String> { |
@@ -37,10 +41,21 @@ fn main() { |
37 | 41 | let app_root = span!(tracing::Level::INFO, "app_start"); |
38 | 42 |
|
39 | 43 | // 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 | + }); |
45 | 60 | }); |
46 | 61 | } |
0 commit comments