DEV Community

Koma/こま
Koma/こま

Posted on

5

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay