Logging
Ktor client provides the capability to log HTTP calls using the Logging plugin. This plugin provides different logger types for different platforms:
On JVM, Ktor uses SLF4J API as a facade for various logging frameworks (for example, Logback or Log4j).
For Native targets, the
Logging
plugin provides a logger that prints everything toSTDOUT
.For multiplatform projects, you can specify a custom logger (for example, Napier).
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>You can learn more about artifacts required by the Ktor client from Adding client dependencies.
Install Logging
To install Logging
, pass it to the install
function inside a client configuration block:
Configure Logging
The Logging
plugin configuration is provided by the Logging.Config class. The example below shows a sample configuration:
The
logger
property is set toLogger.DEFAULT
, which uses an SLF4J logging framework. For Native targets, set this property toLogger.SIMPLE
.The
level
property specifies the logging level. For instance, you can log only request/response headers or include their bodies.The
filter
function allows you to filter log messages for requests matching the specified predicate. In the example below, only requests made toktor.io
get into the log.The
sanitizeHeader
function allows you to sanitize sensitive headers to avoid their values appearing in the logs. In the example below, Authorization header value will be replaced with '***' when logged.
You can find the full example here: client-logging.
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:
For the full example, see client-logging-napier.