How to add a logging interceptor for KTOR?

Viewed 4118

When I was using Retrofit, I could easily create logging interceptors to see the calls with body and headers on the logcat:

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

and then

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

Now, we switched to Ktor and I don't know I dont know how

  • to use addInterceptor()?
  • and for [install(CallLogging)][2] nothing happens..

Any suggestions or examples?

[2] source:

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

Did you configure your logging? Ktor only provides the slf4j api. When you start the server, you should see this:

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.

Which means, that you need to put a logger implementation on the classpath.

The fastest option is probably implementation 'org.slf4j:slf4j-simple:1.7.26'.

Now you should get some logs from the server.

However, by default, only calls are logged.

Headers and body are not logged.

IIRC the body can only be consumed once, but maybe something changed about that.

Headers can be logged with a custom interceptor.

For example:

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

Since you are configuring the call logging feature level to trace, you will need to configure your logging system (whatever sl4j provider you're using) to log ktor.application to trace. E.g. for log4j2.xml:

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

Related