Get the currently active span from implicit context

4.6k views Asked by At

I found this in opentelemetry/specification/trace/api:

If the language has support for implicitly propagated Context (see here), the API SHOULD also provide the following functionality:

  • Get the currently active span from the implicit context. This is equivalent to getting the implicit context, then extracting the Span from the context.
  • Set the currently active span to the implicit context. This is equivalent to getting the implicit context, then inserting the Span to the context.

But I didn't find the method to get the currently active span in java or go. Is there any language that support this feature?
Any help will be appreciated!

2

There are 2 answers

0
Triynko On

Yes, .NET supports it: global::OpenTelemetry.Trace.Tracer.CurrentSpan. This works, because there can be only one 'active' span in any given execution flow at a time. To be clear: there can be more than one span concurrently active, just not in the same execution flow; execution flows can fork, but each fork has only one active span at a time.

Also, .NET already has the equivalent of the OpenTelemetry API in its Activity API.

  • Tracer is a wrapper around ActivitySource.
  • TelemetrySpan is a wrapper around Activity.

You can also get the current System.Diagnostics.ActivityContext by accessing Activity.Current.Context.

The OpenTelemetry API's .NET reference implementation recommends that you just use the .NET framework's built-in Activity API directly. However, it also provides OpenTelemetry shims that wrap the Activity API.

For example, you can implicitly convert an OpenTelemetry.Trace.SpanContext to a System.Diagnostics.ActivityContext. And you can convert it back with new OpenTelemetry.Trace.SpanContext(activityContext).

I don't see a method to get a TelemetrySpan from a SpanContext; however. So global::OpenTelemetry.Trace.Tracer.CurrentSpan is probably your best bet.

0
AndrWeisR On

Current span in Java is simply Span.current().

This code snippet creates a child span of the current span:

Span childSpan = tracer.spanBuilder("This is a child span")
                        .setParent(Context.current().with(Span.current()))
                        .startSpan();