'How to log http requests in flutter

I am developing an app with flutter and I am using default http package in dart for making API calls. How do we log all the http requests which are going through. Is there any in built feature in http or middleware available for the same?



Solution 1:[1]

There doesn't seem to be a built-in way to log request. However, you can implement your own Client to log request:

class MyClient extends BaseClient {
  MyClient(this.delegate);
  final Client delegate;
  Future<StreamedResponse> send(BaseRequest request) {
    _logRequest(request);
    return delegate.send(request);
  }
  void close() => delegate.close();
  void _logRequest(BaseRequest request) => ....;
}

Solution 2:[2]

Just debugging solution as is

class LoggableHttpClient extends BaseClient {
  final Client _delegate;
  final Logger _logger;

  LoggableHttpClient(this._delegate, this._logger);

  @override
  void close() {
    _delegate.close();
  }

  @override
  Future<StreamedResponse> send(BaseRequest request) async {
    String s = "${request.method} ${request.url} -->";
    s += "\nheader: ${request.headers}";
    if(request is Request && request.body.length>0) {
      s += "\nbody: ${request.body}";
    }
    _logger.info(s);
    final response =  await _delegate.send(request);
    s = "${request.method} ${request.url} <--";
    s += "\nheader: ${response.headers}";

    // Simple request
    if(request is Request) {
      final List<int> bytes = await response.stream.toBytes();
      s += "\nbody: ${await utf8.decode(bytes)}";
      _logger.info(s);

      return StreamedResponse(
          ByteStream.fromBytes(bytes),
          response.statusCode,
          contentLength: response.contentLength,
          request: request,
          headers: response.headers,
          isRedirect: response.isRedirect,
          persistentConnection: response.persistentConnection,
          reasonPhrase: response.reasonPhrase
      );
    }

    _logger.info(s);

    return response;
  }
}

Solution 3:[3]

You can user http_logger Add them to you pubspec.yaml like this

  http: ^0.11.3+16
  http_middleware: ^1.0.0
  http_logger: ^1.0.0

Note that: http_logger 1.0.0 only works with http 0.11.3+16. (update 02/04/2020).

And import them to file like this:

import 'package:http_middleware/http_middleware.dart';
import 'package:http_logger/http_logger.dart';
import 'package:http/http.dart' as http;

And use them :

HttpWithMiddleware httpClient = HttpWithMiddleware.build(middlewares: [
      HttpLogger(logLevel: LogLevel.BODY),
    ]);
    final http.Response response = await httpClient.post(
      "https:nhatvm.com/v1/user/login",
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{'email': email, 'password': password}),
    );

Solution 4:[4]

You can use requests_inspector package.

void main() {
  runApp(const RequestsInspector(
    enabled: true,
    child: MyApp(),
  ));
}

Screenshots

screenshot example

Note: Don't forget to add the request using RequestsInspectorInterceptor or using InspectorController.addRequest().

Solution 5:[5]

You can user pretty_http_logger Add it to your pubspec.YAML like this

  pretty_http_logger: ^0.2.1

And use it like this:

HttpWithMiddleware http = HttpWithMiddleware.build(middlewares: [
    HttpLogger(logLevel: LogLevel.BODY),
]);

That is it! Now go ahead and use this http object as you would normally do.

Simple POST request

var response = await http.post('https://jsonplaceholder.typicode.com/posts/',
    body: {"testing", "1234"});

Simple GET request

var response = await http.get('https://jsonplaceholder.typicode.com/posts/');

It will print out all the headers, request body, response, and error in a proper format that is easy to read and looks pretty.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexandre Ardhuin
Solution 2 A.Y.
Solution 3 NhatVM
Solution 4 Abdelazeem Kuratem
Solution 5 Mithun Adhikari