traceContext<T> function
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();
}
}