2

I'm using the Dart Shelf package and I need to log the response it sends.

I've managed to log the request but the response technique is less clear:

final handler = const shelf.Pipeline()
        .addMiddleware(corsHeaders())
        .addMiddleware(shelf.logRequests(
            logger: (message, isError) =>
                _logRequest(message, isError: isError)))
        .addHandler((req) async {
      final res = await Router().call(req);
      return res;
    });

There two parts to the question.

  1. how do I log the headers.
  2. is it possible to log the body. I know there is an issue in that the response body can only be read once.

As some of the responses are likely to be large I need to filter the requests for which the body is logged.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Brett Sutton
  • 3,900
  • 2
  • 28
  • 53

1 Answers1

3

The answer is a bit of Dart-fu. You have an anonymous function returning an anonymous function.

var handler = const Pipeline()
    .addMiddleware(
      (handler) => (request) async {
        final response = await handler(request);
        print(response.headers);
        // you could read the body here, but you'd also need to 
        // save the content and pipe it into a new response instance
        return response;
      },
    )
    .addHandler(syncHandler);
Kevin Moore
  • 5,921
  • 2
  • 29
  • 43