traceSync<T> function

  1. @experimental
T traceSync<T>(
  1. String name,
  2. T fn(), {
  3. Context? context,
  4. Tracer? tracer,
  5. bool newRoot = false,
  6. SpanKind spanKind = api.SpanKind.internal,
  7. List<SpanLink> spanLinks = const [],
})

Use traceSync instead of trace when fn is not an async function.

Implementation

@experimental
T traceSync<T>(String name, T Function() fn,
    {api.Context? context,
    api.Tracer? tracer,
    bool newRoot = false,
    api.SpanKind spanKind = api.SpanKind.internal,
    List<api.SpanLink> spanLinks = const []}) {
  context ??= api.Context.current;
  tracer ??= _tracerProvider.getTracer('opentelemetry-dart');

  final span = tracer.startSpan(name,
      // TODO: use start span option `newRoot` instead
      context: newRoot ? api.Context.root : context,
      kind: spanKind,
      links: spanLinks);
  try {
    return Zone.current.fork().run(() {
      final token = api.Context.attach(api.contextWithSpan(context!, span));

      final r = fn();

      if (!api.Context.detach(token)) {
        span.addEvent('unexpected (mismatched) token given to detach');
      }

      if (r is Future) {
        throw ArgumentError.value(fn, 'fn',
            'Use traceSync to trace functions that do not return a [Future].');
      }
      return r;
    });
  } catch (e, s) {
    span
      ..setStatus(api.StatusCode.error, e.toString())
      ..recordException(e, stackTrace: s);
    rethrow;
  } finally {
    span.end();
  }
}