Propagators are used to extract and inject context data across service boundaries. They enable distributed tracing by passing trace context and baggage between services using standard formats like W3C Trace Context.
The default propagator implementing the W3C Trace Context specification:
use opentelemetry::global;use opentelemetry_sdk::propagation::TraceContextPropagator;// Set the global propagatorglobal::set_text_map_propagator(TraceContextPropagator::new());
The Injector trait is implemented by carriers that can have context injected into them:
pub trait Injector { /// Add a key and value to the underlying data fn set(&mut self, key: &str, value: String); /// Hint to reserve capacity for additional entries fn reserve(&mut self, additional: usize) {}}
HashMap implementation:
use std::collections::HashMap;use opentelemetry::propagation::Injector;let mut headers = HashMap::new();headers.set("traceparent", "00-trace-id-span-id-01".to_string());
The Extractor trait is implemented by carriers that can have context extracted from them:
pub trait Extractor { /// Get a value from a key fn get(&self, key: &str) -> Option<&str>; /// Collect all keys fn keys(&self) -> Vec<&str>; /// Get all values from a key fn get_all(&self, key: &str) -> Option<Vec<&str>>;}
use opentelemetry::global;use opentelemetry::Context;use std::collections::HashMap;// Get the current context with active spanlet cx = Context::current();// Prepare headerslet mut headers = HashMap::new();// Inject context into headersglobal::get_text_map_propagator(|propagator| { propagator.inject_context(&cx, &mut headers);});// Use headers in HTTP requestfor (key, value) in headers { // request.header(key, value);}