skip to Main Content

I need to Log a full requisition Body, one single time on each req that my system does. I’am using StringBuffer, Dio and LogInterceptor.

What happens:

My log is printing the building of the body, not the full body’s req.

CODE:

if (kDebugMode) {
  StringBuffer logObject = StringBuffer();
  dio.interceptors.add(
    LogInterceptor(
      requestBody: true,
      responseBody: true,
      requestHeader: true,
      responseHeader: true,
      error: true,
      logPrint: (Object object) {
        logObject.writeln(object);
        djLogger.debug(
          content: "Value Custom DIO: ",
          value: logObject,
        );
      },
    ),
  );
}

What I’ve tried

I tried to log the logObject outside the dio.interceptors.add(), but the result of my log was Null.

2

Answers


  1. You can simply use a log method for get full req body printed.

    import 'dart:developer';
    
    log('data: $data');
    
    Login or Signup to reply.
  2. Well I hope you are using a common network class to access the same dio instance for all your network calls. If yes, then you can try the following:

    So, let’s say you initialized a Dio object.

    Dio dio = Dio();
    

    You can add log or any type of interceptors to that dio object. For adding only one inteceptor, you can do the following:

    dio.interceptors.add(Logging(dio));
    

    Here is the logging interceptor class:

    class Logging extends Interceptor {
      final Dio dio;
    
      Logging(this.dio);
    
      @override
      void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
        log(
            'REQUEST[${options.method}] => PATH: ${options.path} n Extras: ${options.extra} n Headers: ${options.headers} n Query: ${options.queryParameters} n Body: ${options.data}');
        super.onRequest(options, handler);
      }
    
      @override
      void onResponse(Response response, ResponseInterceptorHandler handler) {
        log(
            'RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path} n res:: ${json.encode(response.data)}');
        super.onResponse(response, handler);
      }
    
      @override
      void onError(DioException err, ErrorInterceptorHandler handler) {
        log(
            'ERROR[${err.response?.statusCode ?? 'Unknown Status Code'}] => PATH: ${err.requestOptions.path}');
        super.onError(err, handler);
      }
    }
    

    Hope this helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search