Ktor日志呼叫时长



我正在尝试记录响应时间的呼叫。到目前为止还没有解决方案。

install(CallLogging) {
level = Level.INFO
disableDefaultColors()
format { call ->
val status = call.response.status()
val httpMethod = call.request.httpMethod.value
val path = call.request.path()
// How to access duration
val duration = ???
"$status $httpMethod $path $duration"
}
}

我可能可以ObserveResponse,但是,我将有单独的日志条目为一个调用..

任何想法?

我找到解决办法了。但是很麻烦……

...
import io.ktor.server.plugins.callloging.*
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
...
val CALL_START_TIME = AttributeKey<LocalDateTime>("CallStartTime")
intercept(ApplicationCallPipeline.Setup) {
// intercept before calling routing and mark start of call
call.attributes.put(CALL_START_TIME, LocalDateTime.now())
}
install(CallLogging) {
level = Level.INFO
disableDefaultColors()
format { call ->
val status = call.response.status()
val httpMethod = call.request.httpMethod.value
val path = call.request.path()
val duration = when (val startTime = call.attributes.getOrNull(CALL_START_TIME)) {
null -> "?ms" // just in case
else -> "${startTime.until(LocalDateTime.now(), ChronoUnit.MILLIS)}ms"
}
"$status $httpMethod $path $duration"
}
}
...

希望KTOR将来能提供更优雅的解决方案…

原答案Sergey Mashkov

最新更新