How to set Span Context in current Context?

Viewed 1178

In opentelemetery-api version 0.8.0, we used to set a new SpanContext in current Context via following code:

TracingContextUtils.currentContextWith(DefaultSpan.create(newSpanCtx))

However, in version 0.13.1, both - TracingContextUtils and DefaultSpan are removed. Then how can I set a new SpanContext in the current Context?

2 Answers

From opentelemetry-java version 0.10.0 release notes:

  • TracingContextUtils and BaggageUtils were removed from the public API. Instead, use the appropriate static methods on the Span and Baggage classes, or use methods on the Context itself.
  • DefaultSpan was removed from the public API. Instead, use Span.wrap(spanContext) if you need a non-functional span that propagates the trace context.

You can try something like:

val newSpanCtx: SpanContext = null
val span: Span = Span.wrap(newSpanCtx)
Context.current().`with`(span).makeCurrent()

How about using the scope and calling the makeCurrent method?

Span span = tracer.spanBuilder("my span").startSpan();
// put the span into the current Context
try (Scope scope = span.makeCurrent()) {
    // your use case
    ...
} catch (Throwable t) {
    span.setStatus(StatusCode.ERROR, "Change it to your error message");
} finally {
    span.end(); // closing the scope does not end the span, this has to be done manually
}

This is what the quickstart also states.

Related