You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ktor的CallLogging中记录请求响应耗时?

在Ktor中记录带响应时间的请求日志

方案:自定义监控阶段拦截器

直接通过ApplicationCallPipeline.Monitoring阶段的拦截器,在请求开始时记录时间,处理完成后计算响应时长,避免生成多条日志。

实现代码

install(CallLogging) {
    level = Level.INFO
    disableDefaultColors()
}

// 自定义拦截器记录响应时间
intercept(ApplicationCallPipeline.Monitoring) {
    // 记录请求开始时间
    val startTime = System.currentTimeMillis()
    // 执行后续请求处理流程
    proceed()
    // 计算响应时长
    val duration = System.currentTimeMillis() - startTime
    
    val status = call.response.status() ?: HttpStatusCode.InternalServerError
    val httpMethod = call.request.httpMethod.value
    val path = call.request.path()
    
    // 使用Ktor内置日志器输出统一格式日志
    call.application.log.info("$status $httpMethod $path ${duration}ms")
}

更简洁的写法(使用Kotlin Time API)

如果项目依赖了Kotlin 1.8+标准库或kotlinx-datetime,可以用measureTime简化时长计算:

import kotlin.time.measureTime

intercept(ApplicationCallPipeline.Monitoring) {
    val duration = measureTime {
        proceed()
    }
    
    val status = call.response.status() ?: HttpStatusCode.InternalServerError
    val httpMethod = call.request.httpMethod.value
    val path = call.request.path()
    
    call.application.log.info("$status $httpMethod $path ${duration.inWholeMilliseconds}ms")
}

方案说明

  • ApplicationCallPipeline.Monitoring是Ktor专门用于监控请求生命周期的阶段,拦截器会在请求处理前执行前置逻辑,proceed()触发后续所有请求处理流程,流程结束后再执行后置逻辑(计算时长、打日志),确保每个请求只生成一条日志。
  • 复用了CallLogging的基础配置(日志级别、颜色设置),同时通过自定义逻辑补充了响应时间字段,日志格式完全可控。

内容的提问来源于stack exchange,提问作者WhipsterCZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:50:13