Skip to content

Instantly share code, notes, and snippets.

@guid-empty
Forked from apgapg/logging_interceptor.dart
Created February 2, 2022 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guid-empty/b55f9c36d60a6f7086884e61ffa66cc9 to your computer and use it in GitHub Desktop.
Save guid-empty/b55f9c36d60a6f7086884e61ffa66cc9 to your computer and use it in GitHub Desktop.
Logging interceptor for dio, flutter
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
/// [LoggingInterceptor] is used to print logs during network requests.
/// It's better to add [LoggingInterceptor] to the tail of the interceptor queue,
/// otherwise the changes made in the interceptor behind A will not be printed out.
/// This is because the execution of interceptors is in the order of addition.
class LoggingInterceptor extends Interceptor {
LoggingInterceptor();
@override
Future onRequest(RequestOptions options) async {
logPrint('*** API Request - Start ***');
printKV('URI', options.uri);
printKV('METHOD', options.method);
logPrint('HEADERS:');
options.headers.forEach((key, v) => printKV(' - $key', v));
logPrint('BODY:');
printAll(options.data ?? "");
logPrint('*** API Request - End ***');
}
@override
Future onError(DioError err) async {
logPrint('*** Api Error - Start ***:');
logPrint('URI: ${err.request.uri}');
if (err.response != null) {
logPrint('STATUS CODE: ${err.response.statusCode?.toString()}');
}
logPrint('$err');
if (err.response != null) {
printKV('REDIRECT', err.response.realUri);
logPrint('BODY:');
printAll(err.response?.toString());
}
logPrint('*** Api Error - End ***:');
return err;
}
@override
Future onResponse(Response response) async {
logPrint('*** Api Response - Start ***');
printKV('URI', response.request?.uri);
printKV('STATUS CODE', response.statusCode);
printKV('REDIRECT', response.isRedirect);
logPrint('BODY:');
printAll(response.data ?? "");
logPrint('*** Api Response - End ***');
return response;
}
void printKV(String key, Object v) {
logPrint('$key: $v');
}
void printAll(msg) {
msg.toString().split('\n').forEach(logPrint);
}
void logPrint(String s) {
debugPrint(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment