Add logging to Retrofit2

suggest change

Retrofit requests can be logged with an interceptor. The detail levels are NONE, BASIC, HEADERS, and BODY. See the OkHttp logging interceptor.

  1. Add the dependency to build.gradle:
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
  1. Add the logging interceptor when creating Retrofit:
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
        .addInterceptor(loggingInterceptor)
        .build();
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://example.com/")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Do not leave body logging on in release builds. The log can include secrets such as auth tokens.

Enable detailed logging only in debug builds:

For example:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
if(BuildConfig.DEBUG){
     //print the logs in this case   
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}else{
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
      .addInterceptor(loggingInterceptor)
      .build();

Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("http://example.com/")
      .client(okHttpClient)
      .addConverterFactory(GsonConverterFactory.create(gson))
      .build();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents