tracedAsync<T> function

  1. @experimental
Future<T> tracedAsync<T>(
  1. String label,
  2. Future<T> block()
)

Executes an asynchronous operation while logging its execution time and status.

This function wraps an asynchronous block with automatic timing and logging. It logs the start, completion time (including duration), and any errors that occur. This is useful for performance profiling, debugging, and monitoring the execution of critical operations.

The function returns the same value as block and re-throws any exception it raises, making it transparent to callers: behaviour is identical to calling block directly, with timing and logging added as a side effect.

Logging Output:

  • Start: ▶ <label> started
  • Success: ✓ <label> done in <ms>ms
  • Error: ✗ <label> failed after <ms>ms: <error>

Logs are written using developer.log, which respects Dart's logging configuration and appears in the DevTools timeline and logs.

Type Parameter T: The return type of the operation, can be any value (nullable or non-nullable).

Parameters:

  • label: A descriptive name for the operation, used in log messages.
  • block: An async function that performs the operation and returns a Future.

Returns: The value resolved from the Future returned by block.

Throws: Re-throws any exception thrown by block after logging the failure.

Example:

// Simple operation — note the required await
final data = await tracedAsync('fetch_users', () async {
  return fetchUsers();
});

// Error handling
try {
  await tracedAsync('risky_operation', () async => riskyFunction());
} catch (e) {
  print('Operation failed: $e');
}

See also:

Implementation

@experimental
Future<T> tracedAsync<T>(String label, Future<T> Function() block) async {
  developer.log('▶ $label started');
  final sw = Stopwatch()..start();
  try {
    final result = await block();
    sw.stop();
    developer.log('✓ $label done in ${sw.elapsedMilliseconds}ms');
    return result;
  } catch (e) {
    sw.stop();
    developer.log('✗ $label failed after ${sw.elapsedMilliseconds}ms: $e');
    rethrow;
  }
}