Skip to content

Commit e75efad

Browse files
committed
Fix: make network calls be logged using slf4j.
Now Okhttp's network calls are routed through SLF4J just like rest of SDK/Client APP that uses SDK logs so everything is formatted consistently and appears in the correct chronological order. Previously OkHttp was using the JVM's default java.util.logging, which caused its HTTP-level logs to be emitted separately and sometimes interleaved out of sequence.
1 parent 31e850c commit e75efad

File tree

1 file changed

+18
-1
lines changed
  • pubnub-kotlin/pubnub-kotlin-impl/src/main/kotlin/com/pubnub/internal/managers

1 file changed

+18
-1
lines changed

pubnub-kotlin/pubnub-kotlin-impl/src/main/kotlin/com/pubnub/internal/managers/RetrofitManager.kt

+18-1
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,14 @@ import okhttp3.Call
2222
import okhttp3.OkHttpClient
2323
import okhttp3.logging.HttpLoggingInterceptor
2424
import org.jetbrains.annotations.TestOnly
25+
import org.slf4j.LoggerFactory
26+
import org.slf4j.helpers.NOPLoggerFactory
2527
import retrofit2.Retrofit
2628
import java.util.concurrent.ExecutorService
2729
import java.util.concurrent.TimeUnit
2830

31+
private const val PUBNUB_OKHTTP_REQUEST_RESPONSE_LOGGER_NAME = "pubnub.okhttp"
32+
2933
class RetrofitManager(
3034
val pubnub: PubNubImpl,
3135
private val configuration: PNConfiguration,
@@ -108,7 +112,15 @@ class RetrofitManager(
108112
with(configuration) {
109113
if (logVerbosity == PNLogVerbosity.BODY) {
110114
okHttpBuilder.addInterceptor(
111-
HttpLoggingInterceptor().apply {
115+
HttpLoggingInterceptor { message ->
116+
if (slf4jIsBound()) {
117+
// will follow whatever SLF4J config (logback, log4j2, etc.) is on the classpath
118+
LoggerFactory.getLogger(PUBNUB_OKHTTP_REQUEST_RESPONSE_LOGGER_NAME).debug(message)
119+
} else {
120+
// fallback: always print
121+
println("[$PUBNUB_OKHTTP_REQUEST_RESPONSE_LOGGER_NAME] $message")
122+
}
123+
}.apply {
112124
level = HttpLoggingInterceptor.Level.BODY
113125
},
114126
)
@@ -144,6 +156,11 @@ class RetrofitManager(
144156
return okHttpClient
145157
}
146158

159+
private fun slf4jIsBound(): Boolean {
160+
val factory = LoggerFactory.getILoggerFactory()
161+
return factory !is NOPLoggerFactory
162+
}
163+
147164
private fun createRetrofit(callFactory: Call.Factory?): Retrofit {
148165
val retrofitBuilder =
149166
Retrofit.Builder()

0 commit comments

Comments
 (0)