I used Retrofit in order to make HTTP requests and JSON parsing and I loved the way to turn on debug logs. Logs allow to see body requests, URL... which is very useful. As Retrofit use OkHttp, I'm wondering if OkHttp also have a way to enable logs for each requests made.
we create and variable called logging of HttpLoggingInterceptor and set the level of logging to Basic. Basic is the initial level in which you can just log reqest and the response of the API. We can also have NONE, HEADERS and BODY. NONE : Logs Nothing.
The Logging Interceptor is a pretty trivial Interceptor which just logs to Jakarta Commons Logging or log4j as messages are sent or acknowledged on a broker. The default logging level used is INFO. If you want to increase/reduce the logging you can use change it via commons logging or log4j.
Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks.
Using an Interceptor
, you can define the following class:
class LoggingInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Log.d("OkHttp", String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); return response; } }
And add it:
OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor()) .build();
The interceptors feature is currently in review, but you can build your own version of okHttp with the feature by applying the code changes in the pull request.
You can implement the functionality you want with something like this
// Create an interceptor which catches requests and logs the info you want RequestInterceptor logRequests= new RequestInterceptor() { public Request execute(Request request) { Log.i("REQUEST INFO", request.toString()); return request; // return the request unaltered } }; OkHttpClient client = new OkHttpClient(); List<RequestInterceptor> requestInterceptors = client.requestInterceptors(); requestInterceptros.add(logRequests);
A test is included within the pull request if you want to see more.
I'm going to have to warn you ahead of time about using this. There may be changes to the interceptor API since it has yet to be merged in. Don't use it with production code, but it's innocuous enough for personal testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With