Logging with Retrofit 2

In Retrofit 2 you should use HttpLoggingInterceptor.

Add dependency to build.gradle. Latest version as of October 2019 is:

implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'

Create a Retrofit object like the following:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

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

return retrofit.create(ApiClient.class);

In case of deprecation warnings, simply change setLevel to:

interceptor.level(HttpLoggingInterceptor.Level.BODY);

The above solution gives you logcat messages very similar to the old ones set by

setLogLevel(RestAdapter.LogLevel.FULL)

In case of java.lang.ClassNotFoundException:

Older Retrofit version might require an older logging-interceptor version. Take a look at comments sections for details.

Leave a Comment