withSpanContext method
Creates a new context with the given span context.
Returns a new Context derived from this one with spanContext set,
replacing any existing span context — even one belonging to a
different trace. Per the OpenTelemetry Context specification a
set-value operation always returns a derived Context, and per the
Propagators API specification extract must never throw: receiving a
valid traceparent for another trace while a local span is active is
an ordinary situation, not an error. When the trace ID changes, a
debug log records the replacement. Use withSpan to make a span (and
its span context) current when creating child spans.
Implementation
Context withSpanContext(SpanContext spanContext) {
final currentSpanContext = get<APISpan?>(_spanKey)?.spanContext ??
get<SpanContext?>(_spanContextKey);
if (currentSpanContext != null &&
currentSpanContext.isValid &&
spanContext.isValid &&
currentSpanContext.traceId != spanContext.traceId &&
OTelLog.isDebug()) {
OTelLog.debug('Context.withSpanContext: replacing span context of trace '
'${currentSpanContext.traceId} with span context of trace '
'${spanContext.traceId}.');
}
return copyWith(_spanContextKey, spanContext);
}