HttpLoggingInterceptor not logging with retrofit 2

13,602

Solution 1

Instead of

val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor)
    ...

you should have something like:

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(interceptor)
    ...

as the addNetworkInterceptor() plays with interceptors that observe a single network request and response, while addInterceptor() adds interceptor that observes the full span of each call: from the connection is established (if any) until after the response source is selected (either the origin server, cache, or both).

EDIT

Errors doing requests on Main Thread are not showing by the logger, so be careful

Doing networking on main thread is not an "ordinary" error. It will result in your app being killed by the system with NetworkOnMainThreadException and this will happen before interceptor would be given any chance to run.

Solution 2

private val interceptor = run {
    val httpLoggingInterceptor = HttpLoggingInterceptor()
    httpLoggingInterceptor.apply {
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    }
}


private val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
    .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
    .writeTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()
Share:
13,602
Daniel Gomez Rico
Author by

Daniel Gomez Rico

Me

Updated on July 24, 2022

Comments

  • Daniel Gomez Rico
    Daniel Gomez Rico almost 2 years

    Im trying to log all the requests (with a network interceptor) using refrofit2, kotlin and logging-interceptor:

    • retrofit: "2.0.2"
    • okhttp3 : "3.2.0"
    • com.squareup.okhttp3:logging-interceptor 3.2.0

    like:

    val interceptor = HttpLoggingInterceptor()
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    
        val okHttpClient = OkHttpClient.Builder()
            .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
            .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
            .writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()
    
        sRestAdapter = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(if (host.endsWith("/")) host else "$host/")
            .addConverterFactory(GsonConverterFactory.create(gson()))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build()
    

    It just print:

    D/OkHttp: --> GET url...
    D/OkHttp: --> END GET
    

    What is happening?

    --------------- EDIT --------

    Errors doing requests on Main Thread are not showing by the logger, so be careful.