Hi! Is there a way to log the exact request a Ktor...
# ktor
c
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
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
Thanks, I'll look into that
m
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
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
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
I see. Do you have any tips/clues to how I can do this?
m
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.