DEV Community

Koma/こま
Koma/こま

Posted on

How to create a link between two spans in OpenTelemetry

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.

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});
Enter fullscreen mode Exit fullscreen mode
/* 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)]);
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)