logged<T> method

Future<T> logged<T>(
  1. Future<T> action,
  2. String actionName, {
  3. bool logCallStack = false,
  4. ({LogLevel level, String message, Map<String, dynamic>? structuredData}) resultFormatter(
    1. T result,
    2. int elapsedMilliseconds
    )?,
  5. List<String>? tags,
})

Executes an action, logs the start and end of the action, and returns the result of the action

Implementation

Future<T> logged<T>(
  Future<T> action,
  String actionName, {
  bool logCallStack = false,
  ({String message, Map<String, dynamic>? structuredData, LogLevel level})
  Function(T result, int elapsedMilliseconds)?
  resultFormatter,
  List<String>? tags,
}) async {
  log('Start $actionName');
  if (logCallStack) {
    log('Call Stack\n${StackTrace.current}');
  }
  final stopwatch = Stopwatch()..start();
  try {
    final result = await action;

    final formatterResult =
        resultFormatter?.call(result, stopwatch.elapsedMilliseconds) ??
        (message: result, structuredData: {}, level: LogLevel.trace);

    log(
      logLevel: formatterResult.level,
      'Completed $actionName with no exceptions in '
      '${stopwatch.elapsedMilliseconds}ms with '
      '${formatterResult.message}',
      structuredData: formatterResult.structuredData,
      tags: tags,
    );

    return result;
  } catch (e, s) {
    log(
      'Failed $actionName in ${stopwatch.elapsedMilliseconds}ms',
      logLevel: LogLevel.error,
      fault: Fault.fromObjectAndStackTrace(e, s),
    );
    rethrow;
  }
}