如何在ktor http客户端中记录请求?

Sek*_*eko 5 kotlin okhttp ktor

我得到这样的东西:

private val client = HttpClient {
    install(JsonFeature) {
        serializer = GsonSerializer()
    }
    install(ExpectSuccess)
}
Run Code Online (Sandbox Code Playgroud)

并提出要求

  private fun HttpRequestBuilder.apiUrl(path: String, userId: String? = null) {
    header(HttpHeaders.CacheControl, "no-cache")
    url {
        takeFrom(endPoint)
        encodedPath = path
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我需要检查请求和响应正文,有什么办法吗?在控制台/文件中?

Gio*_*gos 8

您可以使用该Logging功能实现这一点。

首先添加依赖:

implementation "io.ktor:ktor-client-logging-native:$ktor_version"
Run Code Online (Sandbox Code Playgroud)

然后安装该功能:

private val client = HttpClient {
   install(Logging) {
      logger = Logger.DEFAULT
      level = LogLevel.ALL
   }
}
Run Code Online (Sandbox Code Playgroud)

奖金:

如果您需要在HttpClient整个应用程序中拥有多个实例并且想要重用某些配置,那么您可以创建一个扩展函数并在其中添加公共逻辑。例如:

fun HttpClientConfig<*>.default() {
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.ALL
    }

    // Add all the common configuration here.
}
Run Code Online (Sandbox Code Playgroud)

然后HttpClient像这样初始化你:

private val client = HttpClient {
   default()
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*art 7

我也遇到了这个问题。我转而使用Ktor OkHttp客户端,因为我对那里的日志记录机制很熟悉。

更新您的pom.xmlgradle.build以包括该客户端(从Ktor站点复制/粘贴),并添加OkHttp日志记录拦截器(同样,从该站点复制/粘贴)。当前版本是3.12.0

现在用

val client = HttpClient(OkHttp) {
    engine {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = Level.BODY
        addInterceptor(loggingInterceptor)
    }
}
Run Code Online (Sandbox Code Playgroud)


Jac*_*s.S 6

无论您使用哪个客户端或使用哪个框架,您都可以像这样实现自己的记录器:

private val client = HttpClient {
    // Other configurations...
    install(Logging) {
        logger = CustomHttpLogger()
        level = LogLevel.BODY
    }
}
Run Code Online (Sandbox Code Playgroud)

CustomHttpLogger实现 ktor Logger 接口的类在哪里,如下所示:

import io.ktor.client.features.logging.Logger

class CustomHttpLogger(): Logger {
    override fun log(message: String) {
        Log.d("loggerTag", message) // Or whatever logging system you want here
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处的文档此处源代码中阅读有关 Logger 接口的更多信息


Leo*_*nid 0

看起来我们应该处理responsein HttpReceivePipeline。我们可以克隆原始响应并将其用于日志记录目的:

scope.receivePipeline.intercept(HttpReceivePipeline.Before) { response ->
    val (loggingContent, responseContent) = response.content.split(scope)

    launch {
        val callForLog = DelegatedCall(loggingContent, context, scope, shouldClose = false)
        ....
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

示例实现可以在这里找到:https://github.com/ktorio/ktor/blob/00369bf3e41e91d366279fce57b8f4c97f927fd4/ktor-client/ktor-client-core/src/io/ktor/client/features/observer/ResponseObserver.kt 和将在下一个次要版本中作为客户端功能提供。

顺便说一句:我们可以为请求实现相同的方案。