traceSync<T> function
Use traceSync instead of trace when fn
is not an async function.
Implementation
@experimental
T traceSync<T>(String name, T Function() fn,
{api.Context? context,
api.Tracer? tracer,
bool newRoot = false,
api.SpanKind spanKind = api.SpanKind.internal,
List<api.SpanLink> spanLinks = const []}) {
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 Zone.current.fork().run(() {
final token = api.Context.attach(api.contextWithSpan(context!, span));
final r = fn();
if (!api.Context.detach(token)) {
span.addEvent('unexpected (mismatched) token given to detach');
}
if (r is Future) {
throw ArgumentError.value(fn, 'fn',
'Use traceSync 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();
}
}