Ktor 2.0.1 Help

Logging

Ktor client provides the capability to log HTTP calls using the Logging plugin. This plugin provides different logger types for different platforms:

Add dependencies

To enable logging, you need to include the following artifacts in the build script:

  • (Optional) An artifact with the required SLF4J implementation, for example, Logback:

    implementation("ch.qos.logback:logback-classic:$logback_version")
    implementation "ch.qos.logback:logback-classic:$logback_version"
    <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback_version}</version> </dependency>

  • The ktor-client-logging artifact:

    implementation("io.ktor:ktor-client-logging:$ktor_version")
    implementation "io.ktor:ktor-client-logging:$ktor_version"
    <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-client-logging-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install Logging

To install Logging, pass it to the install function inside a client configuration block:

val client = HttpClient(CIO) { install(Logging) }

Configure Logging

The example below shows how to configure the Logging plugin:

  • The logger property is set to Logger.DEFAULT, which uses an SLF4J logging framework. For Native targets, set this property to Logger.SIMPLE.

  • The level property specifies the logging level.

package com.example import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.logging.* import io.ktor.client.request.* import io.ktor.client.statement.* import kotlinx.coroutines.runBlocking fun main() { runBlocking { val client = HttpClient(CIO) { install(Logging) { logger = Logger.DEFAULT level = LogLevel.HEADERS } } val response: HttpResponse = client.get("https://ktor.io/") } }

Provide a custom logger

To use a custom logger in your client application, you need to create a Logger instance and override the log function. The example below shows how to use the Napier library to log HTTP calls:

fun main() { runBlocking { val client = HttpClient(CIO) { install(Logging) { logger = object: Logger { override fun log(message: String) { Napier.v("HTTP Client", null, message) } } level = LogLevel.HEADERS } }.also { Napier.base(DebugAntilog()) } val response: HttpResponse = client.get("https://ktor.io/") } }

You can find the full example here: client-logging-napier.

Last modified: 13 May 2022