trace<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> 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();
}
}