Skip to content

Commit

Permalink
KTOR-6839 Fix double logging response in CallLogging (#4016)
Browse files Browse the repository at this point in the history
(cherry picked from commit 3a605a6)
  • Loading branch information
marychatte authored and e5l committed Apr 5, 2024
1 parent 4b0ed38 commit dc0d311
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package io.ktor.server.plugins.callloging

import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.*
import io.ktor.util.pipeline.*

internal fun MDCHook(phase: PipelinePhase) = object : Hook<suspend (ApplicationCall, suspend () -> Unit) -> Unit> {
Expand All @@ -25,8 +26,13 @@ internal fun MDCHook(phase: PipelinePhase) = object : Hook<suspend (ApplicationC
internal object ResponseSent : Hook<suspend (ApplicationCall) -> Unit> {
override fun install(pipeline: ApplicationCallPipeline, handler: suspend (ApplicationCall) -> Unit) {
pipeline.sendPipeline.intercept(ApplicationSendPipeline.Engine) {
if (call.attributes.contains(responseSentMarker)) return@intercept

call.attributes.put(responseSentMarker, Unit)
proceed()
handler(call)
}
}
}

private val responseSentMarker = AttributeKey<Unit>("ResponseSentTriggered")
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,35 @@ class CallLoggingTest {
assertContains(messages, "INFO: /without [hardcoded=1]")
}

@Test
fun `no double logging when with Status Pages`() = testApplication {
environment {
log = logger
}
application {
install(CallLogging) {
format { it.request.uri }
}
install(StatusPages) {
status(HttpStatusCode.BadRequest) { call, _ ->
call.respond("From StatusPages")
}
}
}
routing {
get {
call.respond(HttpStatusCode.BadRequest)
}
}

client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("From StatusPages", bodyAsText())
}

assertEquals(1, messages.count { it == "INFO: /" })
}

private fun green(value: Any): String = colored(value, Ansi.Color.GREEN)
private fun red(value: Any): String = colored(value, Ansi.Color.RED)
private fun cyan(value: Any): String = colored(value, Ansi.Color.CYAN)
Expand Down

0 comments on commit dc0d311

Please sign in to comment.