Ktor 2.1.1 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:

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

Create a custom plugin

If you want to create plugins, you can use the standard plugins as a reference.

Last modified: 19 July 2022