https://kotlinlang.org logo
#ktor
Title
# ktor
c

CLOVIS

10/22/2020, 3:30 PM
Hi! Is there a way to log the exact request a Ktor client is sending? Not just the headers, but also the full body contents
r

russhwolf

10/22/2020, 3:54 PM
I think it's supposed to happen when you do
LogLevel.BODY
or
LogLevel.ALL
once https://youtrack.jetbrains.com/issue/KTOR-426 is fixed.
c

CLOVIS

10/22/2020, 9:16 PM
Thanks, I'll look into that
m

MJegorovas

10/23/2020, 10:34 AM
In the mean time you can use something like this (I use it for Android):
Copy code
class BodyLoggingInterceptor {
    companion object : HttpClientFeature<Nothing, BodyLoggingInterceptor> {
        override val key: AttributeKey<BodyLoggingInterceptor> =
            AttributeKey("BodyLoggingInterceptor")

        override fun prepare(block: Nothing.() -> Unit): BodyLoggingInterceptor =
            BodyLoggingInterceptor()

        override fun install(feature: BodyLoggingInterceptor, scope: HttpClient) {
            scope.sendPipeline.intercept(HttpSendPipeline.Monitoring) {
                val body = context.body
                if (body is TextContent) {
                    val content = body.text
                    for (i in content.indices step 1024) {
                        Log.d(
                            "BodyLoggingInterceptor",
                            content.substring(i, min(content.length, i + 1024))
                        )
                    }
                }
            }
        }
    }
}
And then just install in the client just as any other feature.
c

CLOVIS

10/23/2020, 6:51 PM
LogLevel.ALL
does print the
BODY
but only for JSON requests, I'm trying to debug a Multipart request 😕
@MJegorovas Thanks for your code, but it's the same thing, it only prints JSON body and not Multipart body... Unless you're certain that it works and then my code is completely wrong, which would explain many things 🤔
m

MJegorovas

10/26/2020, 12:03 PM
Sorry, for not getting back to you earlier. I was unsuccessful to get
MultiPartFormDataContent
content out of it because it is already processed as
List<PreparedPart>
at this point, so you'll need some other way to log this.
c

CLOVIS

10/27/2020, 8:34 AM
I see. Do you have any tips/clues to how I can do this?
m

MJegorovas

10/27/2020, 9:49 AM
If you're using
submitFormWithBinaryData
method to build request you'll need to print your
List<PartData>
content before passing it to that method. I don't have any other thought at the moment.
3 Views