logger static method

Middleware logger({
  1. void logFunction(
    1. String message
    )?,
})

Implementation

static Middleware logger({
  void Function(String message)? logFunction,
}) {
  final log = logFunction ?? print;

  return (request, next) async {
    final stopwatch = Stopwatch()..start();
    final timestamp = DateTime.now().toIso8601String();

    log('[$timestamp] ${request.method} ${request.url.path}');

    try {
      final response = await next();
      stopwatch.stop();
      log('[$timestamp] ${request.method} ${request.url.path} - ${response.toShelfResponse().statusCode} (${stopwatch.elapsedMilliseconds}ms)');
      return response;
    } catch (e) {
      stopwatch.stop();
      log('[$timestamp] ${request.method} ${request.url.path} - ERROR: $e (${stopwatch.elapsedMilliseconds}ms)');
      rethrow;
    }
  };
}