trace<T> function

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

Records a span of the given name for the given function with a given api.Tracer and marks the span as errored if an exception occurs.

Implementation

@experimental
Future<T> trace<T>(String name, Future<T> Function() fn,
    {api.Context? context,
    api.Tracer? tracer,
    bool newRoot = false,
    api.SpanKind spanKind = api.SpanKind.internal,
    List<api.SpanLink> spanLinks = const []}) async {
  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 await Zone.current.fork().run(() {
      final token = api.Context.attach(api.contextWithSpan(context!, span));
      return fn().whenComplete(() {
        if (!api.Context.detach(token)) {
          span.addEvent('unexpected (mismatched) token given to detach');
        }
      });
    });
  } catch (e, s) {
    span
      ..setStatus(api.StatusCode.error, e.toString())
      ..recordException(e, stackTrace: s);
    rethrow;
  } finally {
    span.end();
  }
}