Avoid trying to log formatted Json if Http bodies are not logged.

This commit is contained in:
Benoit Marty 2022-08-24 10:16:57 +02:00
parent 8cec528ac7
commit 2c63dee86a
2 changed files with 8 additions and 2 deletions

View File

@ -42,7 +42,7 @@ internal object NetworkModule {
@Provides
@JvmStatic
fun providesHttpLoggingInterceptor(): HttpLoggingInterceptor {
val logger = FormattedJsonHttpLogger()
val logger = FormattedJsonHttpLogger(BuildConfig.OKHTTP_LOGGING_LEVEL)
val interceptor = HttpLoggingInterceptor(logger)
interceptor.level = BuildConfig.OKHTTP_LOGGING_LEVEL
return interceptor

View File

@ -23,7 +23,9 @@ import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
internal class FormattedJsonHttpLogger : HttpLoggingInterceptor.Logger {
internal class FormattedJsonHttpLogger(
private val level: HttpLoggingInterceptor.Level
) : HttpLoggingInterceptor.Logger {
companion object {
private const val INDENT_SPACE = 2
@ -39,6 +41,10 @@ internal class FormattedJsonHttpLogger : HttpLoggingInterceptor.Logger {
override fun log(@NonNull message: String) {
Timber.v(message)
// Try to log formatted Json only if there is a chance that [message] contains Json.
// It can be only the case if we log the bodies of Http requests.
if (level != HttpLoggingInterceptor.Level.BODY) return
if (message.startsWith("{")) {
// JSON Detected
try {