How to create a link between two spans in OpenTelemetry

RMAG news

Summary

Span links are another way to express relationship between spans.
It is easy to create one in C# with the OpenTelemetry toolkit.
Datadog currently supports span links as a beta feature.

What is a span link?

In OpenTelemetry, there is another type of relationship between spans other than parent/child relationship. It is called Span Link. These are related documentations.

https://opentelemetry.io/docs/concepts/signals/traces/#span-links
https://opentelemetry.io/docs/specs/otel/overview/#links-between-spans
https://opentelemetry.io/docs/specs/otel/trace/api/#link

According to documents above, span links can be used in cases below.

when you want 2 separate traces rather than a single trace
when you want to connect multiple spans onto a span

How to create a span link in C#?

It is easy to create a span link with the OpenTelemetry toolkit. All you have to do is,

Propagate SpanContext of the proceeding span.
Create an ActivityLink and pass it to StartActivity method.

/* Producer side */
// add SpanContext onto the message
Propagators.DefaultTextMapPropagator.Inject(
new PropagationContext(activity.Context, Baggage.Current),
message.MessageAttributes,
(attributes, key, value) => attributes[key] = new MessageAttributeValue {DataType = “String”, StringValue = value});
/* Consumer side */
// extract SpanContext
var context = Propagators.DefaultTextMapPropagator.Extract(
default, message.MessageAttributes,
(attributes, key) => attributes.TryGetValue(key, out var value) ? [value.StringValue] : []);
// start a new span with a link to the producer’s span
using var activity = activitySource.StartActivity(
“ConsumeMessage”, ActivityKind.Consumer,
default(string?), tags, [new ActivityLink(context.ActivityContext)]);

Datadog supports Span Link

Datadog currently supports span links as a beta feature. You can see your span links in span view and move to linked spans with few clicks.

https://github.com/DataDog/datadog-agent/releases/tag/7.45.0
https://github.com/DataDog/datadog-agent/pull/15767
https://docs.datadoghq.com/tracing/trace_explorer/trace_view/?tab=spanlinksbeta#more-information

Leave a Reply

Your email address will not be published. Required fields are marked *