HttpLoggingInterceptor interfering with with refresh token mechanism

Abdul Mateen :

I am facing a very strange issue in my Android app with OkHttp3 Interceptor where I set different logging levels to different build variants.

I have setup an OkHttp3 Interceptor in my app to intercept API requests, and if any API returns 401 error, the interceptor gets the refreshed token from backend and updates the header of original request with the new token and repeats it. Let's call this RefreshTokenInterceptor. I add this interceptor when building my OKHttpClient. Besides this, I also add an HttpLoggingInterceptor to log the API requests and responses or stop logging in case of release builds. Let's call this LoggingInterceptor

Here is the code where I build my OkHttpClient. This code should be enough because the refresh mechanism works fine if the logging level is changed.

val loggingInterceptor = HttpLoggingInterceptor()

// changing level to Level.BODY in the below solves the issue,
// but I don't want to log the results
when {
        BuildConfig.DEBUG -> loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        else -> loggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
}

val httpClientBuilder = OkHttpClient.Builder()
      .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
      .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
      .addInterceptor(ConnectivityInterceptor())
      .addInterceptor(TokenRefreshInterceptor())
      .addInterceptor(loggingInterceptor)
      .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)

When I set the logging level of the LoggingInterceptor in both cases to Level.BODY, everything works fine. But in case of logging level set to Level.NONE, the token refresh mechanism stops working.

To be more specific, in this case, this is what happens in RefreshTokenInterceptor: when a request returns 401, the refresh call is made, but nothing happens afterwards. No success or failure case gets called (Maybe the interceptor Chain breaks but who knows).

Here is what I have tried so far

  • Removing the LoggingInterceptor altogether -> does not work
  • Setting logging level to Level.NONE for all build variants -> does not work
  • Setting logging level to Level.BODY for all build variants -> works like magic

I also searched a lot today on this, but could not find any link between logging levels messing up other interceptors. Any help would be appreciated, and if you need more code, I can post it.

Abdul Mateen :

The problem was being caused by a memory leak which happened because an OkHttp3 Response object in the TokenRefreshInterceptor which was not being closed. I got to know about this leak on Firebase Console. Closing this Response after consuming it solved the issue. But I'm still unsure why it worked fine when I enabled body-level logging.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=350689&siteId=1