Daniel Gomez Rico
Daniel Gomez Rico

Reputation: 15936

HttpLoggingInterceptor not logging with retrofit 2

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

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.

Upvotes: 11

Views: 18587

Answers (2)

Sana Ebadi
Sana Ebadi

Reputation: 7220

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()

Upvotes: 13

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

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.

Upvotes: 12

Related Questions