traceContext<T> function

  1. @experimental
Future<T> traceContext<T>(
  1. String name,
  2. Future<T> fn(
    1. Context
    ), {
  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> traceContext<T>(String name, Future<T> Function(api.Context) fn,
    {api.Context? context,
    api.Tracer? tracer,
    bool newRoot = false,
    api.SpanKind spanKind = api.SpanKind.internal,
    List<api.SpanLink> spanLinks = const []}) async {
  context ??= api.globalContextManager.active;
  tracer ??= _tracerProvider.getTracer('opentelemetry-dart');

  // TODO: use start span option `newRoot` instead
  if (newRoot) {
    context = api.contextWithSpanContext(context, api.SpanContext.invalid());
  }

  final span = tracer.startSpan(name,
      context: context, kind: spanKind, links: spanLinks);
  context = api.contextWithSpan(context, span);
  try {
    // TODO: remove this check once `run` exists on context interface
    if (context is ZoneContext) {
      return await context.run((context) => fn(context));
    }
    return await fn(context);
  } catch (e, s) {
    span
      ..setStatus(api.StatusCode.error, e.toString())
      ..recordException(e, stackTrace: s);
    rethrow;
  } finally {
    span.end();
  }
}