How to log the response for a dart shelf request

Issue

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.

Solution

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);

Answered By – Kevin Moore

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *