traceContextSync<R> function

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

Use traceContextSync instead of traceContext when fn is not an async function.

Implementation

@experimental
R traceContextSync<R>(String name, R Function(api.Context) fn,
    {api.Context? context,
    api.Tracer? tracer,
    bool newRoot = false,
    api.SpanKind spanKind = api.SpanKind.internal,
    List<api.SpanLink> spanLinks = const []}) {
  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 {
    var r;
    // TODO: remove this check once `run` exists on context interface
    if (context is ZoneContext) {
      r = context.run((context) => fn(context));
    } else {
      r = fn(context);
    }

    if (r is Future) {
      throw ArgumentError.value(fn, 'fn',
          'Use traceContextSync 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();
  }
}