Maintaining span context

When viewing a single instance of a span in the BugSnag dashboard, a waterfall diagram will show you that instance’s children and their children, and so on, where the children are spans started from within the context of their parent. This page describes the tools available in the SDK to control these parent-child relationships.

Automatic context creation

By default, when a span is created it becomes the parent span for other spans that start after it. We call this parent span the “current span context” and it remains until it is ended or another span becomes the current context.

For example, in the following snippet span1 becomes the current span context and span2 automatically becomes a child of span1. span3 then becomes the new current context, but with no parent span because span1 and span2 have already ended.

final span1 = bugsnag_performance.startSpan("span1");
final span2 = bugsnag_performance.startSpan("span2");
span2.end();
span1.end();
final span3 = bugsnag_performance.startSpan("span3");
span3.end();

Preventing new contexts

To prevent a span becoming the new current context when it is created, and so being the parent of future spans, set the makeCurrentContext span option:

For example, in the following snippet span1 becomes the parent of both span2 and span3:

final span1 = bugsnag_performance.startSpan('span1');
final span2 = bugsnag_performance.startSpan('span2', makeCurrentContext: false);
final span3 = bugsnag_performance.startSpan('span3');

Setting contexts manually

You can set a parent of a span manually using the parentContext span option:

 final parentSpan = bugsnag_performance.startSpan('parent-span');
runZoned(() {
  final childSpan = bugsnag_performance.startSpan('child-span', parentContext: parentSpan);
}, zoneValues: {});

If a span is known to be independent of any other open spans, you can also set parentContext to BugsnagPerformanceSpanContext.invalid, which will prevent it becoming a child:

bugsnag_performance.startSpan('top-level', parentContext: BugsnagPerformanceSpanContext.invalid);