From 1b8416fe8a9ddb0b4438137c5a631b32358e77cb Mon Sep 17 00:00:00 2001 From: "Aleksei.Tirman" Date: Fri, 20 Dec 2024 14:37:58 +0200 Subject: [PATCH] Log connection failures --- .../io/ktor/client/plugins/logging/Logging.kt | 9 +++++++++ .../client/plugins/logging/NewFormatTest.kt | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt index 9c357b5baf..0e584dfcd8 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/Logging.kt @@ -397,6 +397,14 @@ public val Logging: ClientPlugin = createClientPlugin("Logging", if (stdFormat) { logRequestStdFormat(request) + + try { + proceed() + } catch (cause: Throwable) { + logger.log("<-- HTTP FAILED: $cause") + throw cause + } + return@on } @@ -565,6 +573,7 @@ private object SendHook : ClientHook) { suspend fun proceedWith(content: Any) = context.proceedWith(content) + suspend fun proceed() = context.proceed() } override fun install( diff --git a/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/test/io/ktor/client/plugins/logging/NewFormatTest.kt b/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/test/io/ktor/client/plugins/logging/NewFormatTest.kt index c77441a5a4..832fb40344 100644 --- a/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/test/io/ktor/client/plugins/logging/NewFormatTest.kt +++ b/ktor-client/ktor-client-plugins/ktor-client-logging/jvm/test/io/ktor/client/plugins/logging/NewFormatTest.kt @@ -23,9 +23,11 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.test.runTest import kotlinx.io.readByteArray import org.junit.jupiter.api.BeforeEach +import java.net.UnknownHostException import kotlin.coroutines.CoroutineContext import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertTrue class NewFormatTest { @@ -724,6 +726,21 @@ class NewFormatTest { .assertNoMoreLogs() } + @Test + fun connectFailed() = testWithLevel(LogLevel.INFO, handle = { respondOk() }) { client -> + client.sendPipeline.intercept(HttpSendPipeline.Engine) { + throw UnknownHostException("reason") + } + + assertFailsWith { + client.get("/") + } + + log.assertLogEqual("--> GET /") + .assertLogEqual("<-- HTTP FAILED: java.net.UnknownHostException: reason") + .assertNoMoreLogs() + } + private fun MockRequestHandleScope.respondWithLength(): HttpResponseData { return respond("", headers = Headers.build { append("Content-Length", "0")