gpt4 book ai didi

logging - 如何为 KTOR 添加日志拦截器?

转载 作者:行者123 更新时间:2023-12-05 07:22:35 32 4
gpt4 key购买 nike

当我使用 Retrofit 时,我可以轻松地创建日志记录拦截器以在 logcat 上查看带有正文和 header 的调用:

 val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
val httpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)

然后

 val retrofit = retrofit2.Retrofit.Builder()
.client(httpClient.build())

现在,we switched to Ktor我不知道我不知道怎么办

  • 使用addInterceptor()
  • 对于 [install(CallLogging)][2] 没有任何反应..

有什么建议或例子吗?

[2] 来源:

fun Application.main() {
install(CallLogging){
level = Level.TRACE
}
}

最佳答案

您是否配置了日志记录? Ktor 只提供了 slf4j api。启动服务器时,您应该会看到:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

这意味着,您需要在类路径中放置一个记录器实现。

最快的选择可能是implementation 'org.slf4j:slf4j-simple:1.7.26'

现在您应该从服务器获取一些日志。

但是,默认情况下,只会记录调用。

不记录标题和正文。

IIRC body 只能消耗一次,但也许有些事情改变了。

可以使用自定义拦截器记录 header 。

例如:

call.request.headers.entries()
.map { it.key to it.value.joinToString(",") }
.joinToString(";") { "${it.first}:${it.second}" }

关于logging - 如何为 KTOR 添加日志拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56457143/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com