【问题标题】:How to add a logging interceptor for KTOR?如何为 KTOR 添加日志拦截器?
【发布时间】:2019-10-20 18:23:57
【问题描述】:

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

 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
    }
}

【问题讨论】:

  • 我在导入 io.ktor.features 时遇到问题什么问题?
  • @TimCastelijns io.ktor.features 来自哪里?显然实现“io.ktor:ktor-features:$ktor_version”对我不起作用
  • 它似乎内置于“此功能在类 io.ktor.features.CallLogging 中定义,不需要额外的工件。”尝试省略导入
  • 不,这不是问题所在。我只有` implementation "io.ktor:ktor-client-okhttp:$ktor_version"`。所以我添加了:` implementation "io.ktor:ktor-server-netty:$ktor_version"`

标签: logging kotlin ktor


【解决方案1】:

您是否配置了日志记录? 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 身体只能食用一次,但可能会有所改变。

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

例如:

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

【讨论】:

    【解决方案2】:

    由于您正在配置要跟踪的呼叫记录功能级别,因此您需要配置您的日志系统(无论您使用什么 sl4j 提供程序)来记录 ktor.application 以进行跟踪。例如。对于 log4j2.xml:

    <Logger name="ktor.application" level="trace"/>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2021-04-22
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      相关资源
      最近更新 更多