How to enable Android retrofit2 network library logging?

Standard

As any one who had an experiment with retrofit2 knows, logging is some times required to check what is happening!

Since the retrofit2 required HTTP layer is now completely based on OkHttp, the developers of OkHttp added a logging interceptor in release 2.6.0

add to your build.gradle file:

dependencies {
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
    ...
}

and this is how to build retrofit:

Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(Consts.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());

        //show retrofit logs if is debugging
        if (sIsDebug) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addInterceptor(logging);

            builder.client(httpClient.build());
        }

        mRetrofit = builder.build();

now have fun with logs at logcat…