Ktor 2.3.12 Help

Plugins

Many applications require common functionality that is out of scope of the application logic. This could be things like logging, serialization, or authorization. All of these are provided in Ktor by means of what we call Plugins.

Add plugin dependency

A plugin might require a separate dependency. For example, the Logging plugin requires adding the ktor-client-logging artifact in the build script:

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>

You can learn which dependencies you need from a topic for a required plugin.

Install a plugin

To install a plugin, you need to pass it to the install function inside a client configuration block. For example, installing the Logging plugin looks as follows:

import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.logging.* val client = HttpClient(CIO) { install(Logging) }

Configure a plugin

You can configure a plugin inside the install block. For example, for the Logging plugin, you can specify the logger, logging level, and condition for filtering log messages:

runBlocking { val client = HttpClient(CIO) { install(Logging) { logger = Logger.DEFAULT level = LogLevel.HEADERS filter { request -> request.url.host.contains("ktor.io") } sanitizeHeader { header -> header == HttpHeaders.Authorization }

Create a custom plugin

To learn how to create custom plugins, refer to Custom plugins.

Last modified: 02 April 2024