logRequests function

Middleware logRequests(
  1. {void logger(
    1. String message,
    2. bool isError

Middleware which prints the time of the request, the elapsed time for the inner handlers, the response's status code and the request URI.

If logger is passed, it's called for each request. The msg parameter is a formatted string that includes the request time, duration, request method, and requested path. When an exception is thrown, it also includes the exception's string and stack trace; otherwise, it includes the status code. The isError parameter indicates whether the message is caused by an error.

If logger is not passed, the message is just passed to print.


Middleware logRequests({void Function(String message, bool isError)? logger}) =>
    (innerHandler) {
      final theLogger = logger ?? _defaultLogger;

      return (request) {
        var startTime = DateTime.now();
        var watch = Stopwatch()..start();

        return Future.sync(() => innerHandler(request)).then((response) {
          var msg = _message(startTime, response.statusCode,
              request.requestedUri, request.method, watch.elapsed);

          theLogger(msg, false);

          return response;
        }, onError: (Object error, StackTrace stackTrace) {
          if (error is HijackException) throw error;

          var msg = _errorMessage(startTime, request.requestedUri,
              request.method, watch.elapsed, error, stackTrace);

          theLogger(msg, true);

          // ignore: only_throw_errors
          throw error;