Reputation: 1694
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
Level.NONE
for all build variants -> does
not workLevel.BODY
for all build variants -> works
like magicI 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.
Upvotes: 3
Views: 449
Reputation: 1694
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.
Upvotes: 2