This article was translated from Japanese by Claude Code.
I thought of this, looked it up, and it was quick and convenient so here’s a note 📝
HttpLoggingInterceptor#
OkHttp provides a convenient Interceptor called HttpLoggingInterceptor. By using this class, you can easily check headers, response and request bodies during API communication in Logcat.
For basic usage and available settings, I recommend reading the README below.
By using this class, you can check response and request body values, but with default settings, JSON and array values displayed in Logcat are not formatted. Here I’ll briefly introduce how to format the content before displaying it in logs.
Formatting Log Data#
HttpLoggingInterceptor allows you to pass a Logger via the constructor. By default, a Logger provided by the library is set that simply displays the log.
// HttpLoggingInterceptor.kt
class HttpLoggingInterceptor @JvmOverloads constructor(
private val logger: Logger = Logger.DEFAULT
) : Interceptor {
...
interface Logger {
fun log(message: String)
companion object {
/** A [Logger] defaults output appropriate for the current platform. */
@JvmField
val DEFAULT: Logger = object : Logger {
override fun log(message: String) {
Platform.get().log(message) // Simply displays the log
}
}
}
}
...How to Format#
By defining a custom HttpLoggingInterceptor.Logger and passing it to the HttpLoggingInterceptor constructor, you can control what values are displayed in logs.
Here are implementation examples using Gson and Moshi.
Gson#
internal object InterceptorLogger : HttpLoggingInterceptor.Logger {
private val gson = GsonBuilder().setPrettyPrinting().create()
override fun log(message: String) {
if (message.isJsonOrArray()) {
Platform.get().log(gson.toJson(JsonParser.parseString(message)))
} else {
Platform.get().log(message)
}
}
}
private fun String.isJsonOrArray() = startsWith('{') || startsWith('[')With Gson, by initializing with setPrettyPrinting(), it returns formatted JSON values.
Moshi#
// Moshi
internal class InterceptorLogger(moshi: Moshi) : HttpLoggingInterceptor.Logger {
private val adapter = moshi.adapter(Any::class.java).indent(" ")
override fun log(message: String) {
if (message.isJsonOrArray()) {
val jsonValue = JsonReader.of(Buffer().writeUtf8(message)).readJsonValue()
Platform.get().log(adapter.toJson(jsonValue))
} else {
Platform.get().log(message)
}
}
}
private fun String.isJsonOrArray() = startsWith('{') || startsWith('[')With Moshi, you can set indent on the adapter. It nicely inserts indentation at each level for formatting.