OkHttp - Enable logs

Jul picture Jul · Jul 25, 2014 · Viewed 26.3k times · Source

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.

Answer

James McCracken picture James McCracken · Jun 3, 2015

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