logged<T> method
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;
}
}