Skip to content

Commit

Permalink
Fix Span.current() behavior - return Optional.empty() if there is no …
Browse files Browse the repository at this point in the history
…current span (#8574)

Signed-off-by: Tim Quinn <tim.quinn@oracle.com>
  • Loading branch information
tjquinno authored Mar 27, 2024
1 parent 37a8530 commit fae450c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,17 @@ public static Tracer globalTracer() {
* @return optional of the current span
*/
public static Optional<Span> activeSpan() {
// OTel returns a no-op span if there is no current one.
io.opentelemetry.api.trace.Span otelSpan = io.opentelemetry.api.trace.Span.current();
io.opentelemetry.context.Context otelContext = io.opentelemetry.context.Context.current();

// OTel returns empty baggage if there is no current one.
// OTel Span.current() returns a no-op span if there is no current one. Use fromContextOrNull instead to distinguish.
io.opentelemetry.api.trace.Span otelSpan =
io.opentelemetry.api.trace.Span.fromContextOrNull(otelContext);

if (otelSpan == null) {
return Optional.empty();
}

// OTel Baggage.current() returns empty baggage if there is no current one. That's OK for baggage.
io.opentelemetry.api.baggage.Baggage otelBaggage = io.opentelemetry.api.baggage.Baggage.current();

// Create the span directly with the retrieved baggage. Ideally, it will be our writable baggage because we had put it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,11 @@ void testActiveSpanScopeWithBaggage() {
outerSpan.end(e);
}

// There was no active span before outerSpan was activated, so expect the "default" ad-hoc span ID of all zeroes.
// There was no active span before outerSpan was activated, so expect an empty current span.
Optional<Span> currentSpanAfterTryResourcesBlock = Span.current();
assertThat("Current span just after try-resources block",
currentSpanAfterTryResourcesBlock,
OptionalMatcher.optionalPresent());
assertThat("Current span just after try-resources block",
currentSpanAfterTryResourcesBlock.get().context().spanId(),
containsString("00000000"));
OptionalMatcher.optionalEmpty());
}


Expand Down

0 comments on commit fae450c

Please sign in to comment.