Add Http Logging to Retrofit2 (Request and Response)

Jul 22, 2018

You need HttpLoggingInterceptor. Log shall be output to Logcat.

  • NONE
  • BASIC
  • HEADERS
  • BODY
val okHttpClientBuilder = OkHttpClient.Builder()          .readTimeout(30, TimeUnit.SECONDS)          .writeTimeout(30, TimeUnit.SECONDS)if (BuildConfig.DEBUG) {    val logging = HttpLoggingInterceptor()    logging.level = HttpLoggingInterceptor.Level.BASIC    okHttpClientBuilder.addInterceptor(logging)}val retrofit = Retrofit.Builder()        .baseUrl(URL)        // .addConverterFactory(MoshiConverterFactory.create(moshi))        // .addCallAdapterFactory(CoroutineCallAdapterFactory())        .client(okHttpClientBuilder.build())        .build()val service = retrofit.create(TravelopyPubService::class.java)

build.gradle (Module)

dependencies {
    // https://github.com/square/retrofit/releases
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    // https://github.com/square/okhttp/releases
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    // https://mvnrepository.com/artifact/com.squareup.okhttp3/logging-interceptor
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
}

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.