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

时间:2018-11-06 08:18:50

标签: kotlin okhttp ktor

我有这样的东西:

private val client = HttpClient {
    install(JsonFeature) {
        serializer = GsonSerializer()
    }
    install(ExpectSuccess)
}

并像这样发出请求

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

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

5 个答案:

答案 0 :(得分:4)

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

更新您的pom.xmlgradle.build以包括该客户端(从Ktor站点复制/粘贴),并添加OkHttp Logging Interceptor(再次从该站点复制/粘贴)。当前版本为3.12.0

现在使用以下方式配置客户端

val client = HttpClient(OkHttp) {
    engine {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = Level.BODY
        addInterceptor(loggingInterceptor)
    }
}

答案 1 :(得分:4)

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

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

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

您可以在the documentation heresource code here

中了解有关Logger界面的更多信息。

答案 2 :(得分:2)

查看Kotlin日志记录https://github.com/MicroUtils/kotlin-logging,它被许多开放源代码框架使用,并负责所有漂亮的打印。

您可以像这样简单地使用它:

 private val logger = KotlinLogging.logger {  }
 logger.info { "MYLOGGER INFO" }
 logger.warn { "MYLOGGER WARNING" }
 logger.error { "MYLOGGER ERROR" }

这将在控制台上打印消息。

答案 3 :(得分:2)

您可以使用Logging功能来实现。

首先添加依赖项:

implementation "io.ktor:ktor-client-logging-native:$ktor_version"

然后安装该功能:

private val client = HttpClient {
   install(Logging) {
      logger = Logger.DEFAULT
      level = LogLevel.ALL
   }
}

奖金:

如果您需要在整个应用程序中拥有多个HttpClient实例,并且想要重用某些配置,则可以创建扩展功能并在其中添加通用逻辑。例如:

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

    // Add all the common configuration here.
}

然后像这样初始化HttpClient

private val client = HttpClient {
   default()
}

答案 4 :(得分:1)

似乎我们应该处理response中的HttpReceivePipeline。我们可以克隆原始响应并将其用于记录目的:

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

    launch {
        val callForLog = DelegatedCall(loggingContent, context, scope, shouldClose = false)
        ....
    }
    ...
}

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

btw:我们可以为请求实现相同的方案。

相关问题