Add logging to Retrofit2
suggest changeRetrofit requests can be logged with an interceptor. The detail levels are NONE, BASIC, HEADERS, and BODY. See the OkHttp logging interceptor.
- Add the dependency to
build.gradle:
compile 'com.squareup.okhttp3:logging-interceptor:3.8.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();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents