To propagate tracing information across process boundaries (e.g., via HTTP headers), use W3CTraceContext. This struct wraps a SpanContext and an optional tracestate string for vendor-specific metadata.
Important: W3CTraceContext is a boundary wrapper. Converting a W3CTraceContext to a SpanContext (e.g., when starting a new Span) will discard the tracestate. If you need to preserve tracestate for outbound propagation, you must store the W3CTraceContext or the tracestate string separately.
Encoding for Outbound Requests
Use encode_headers() to get a list of key-value pairs (e.g., for HTTP headers). It always includes traceparent and includes tracestate only if it is present.
Decoding from Inbound Requests
- From raw strings: Use
W3CTraceContext::decode(traceparent, tracestate). - From header iterators: Use
W3CTraceContext::decode_headers(headers). This method is case-insensitive for header names and handles multiple tracestate headers by joining them with commas per the W3C spec.
use fastrace::collector::W3CTraceContext;
use fastrace::prelude::*;
// 1. Decoding from incoming HTTP headers
let headers = vec![
("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"),
("tracestate", "rw=frontend,congo=t61rcWkgMzE"),
];
let ctx = W3CTraceContext::decode_headers(headers).unwrap();
// 2. Starting a new span using the extracted context
// Note: tracestate is NOT carried into the span
let root = Span::root("server", ctx.span_context);
// 3. Encoding for outgoing HTTP headers
let outgoing_headers = ctx.encode_headers();
// returns: [("traceparent", "..."), ("tracestate", "...")]