Ktor 1.6.2 Help


Ktor provides the capability to log application events using the SLF4J library. You can also install and configure the CallLogging plugin to log client requests.

Add dependencies

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

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

Access the logger

The Logger instance is represented by a class that implements the Logger interface. The Logger instance in a Ktor application is created when building the application environment, and this instance is assigned to the ApplicationEnvironment.log property. You can access the Logger from ApplicationCall using the call.application.environment.log property:

routing { get("/api/v1") { call.application.environment.log.info("Hello from /api/v1!") } }

You can also get access to the Logger using Application.log.

Call logging

The CallLogging plugin (previously known as feature) allows you to log incoming client requests.

To install the CallLogging plugin, pass it to the install function in the application initialization code. This can be the main function ...

import io.ktor.features.* // ... fun Application.main() { install(CallLogging) // ... }

... or a specified module.

import io.ktor.features.* // ... fun Application.module() { install(CallLogging) // ... }

You can configure CallLogging in multiple ways: specify a logging level, filter requests based on a specified condition, customize log messages, and so on. You can see the available configuration settings at CallLogging.Configuration.

Set the logging level

By default, Ktor uses the Level.TRACE logging level. To change it, use the level property:

import org.slf4j.event.Level // ... install(CallLogging) { level = Level.INFO }

Filter log requests

The filter property allows you to add conditions for filtering requests. In the example below, only requests made to /api/v1 get into a log:

install(CallLogging) { filter { call -> call.request.path().startsWith("/api/v1") } }

Customize a log message format

By using the format function, you can put any data related to a request into a log. The example below shows how to show a User-Agent header value in a log:

install(CallLogging) { format { call -> call.request.headers["User-Agent"].toString() } }

Put call parameters in MDC

The CallLogging plugin supports MDC (Mapped Diagnostic Context). You can put a desired context value with the specified name to MDC using the mdc function. For example, in the code snippet below, a name query parameter is added to MDC:

install(CallLogging) { mdc("name-parameter") { call -> call.request.queryParameters["name"] } }

You can access the added value during an ApplicationCall lifetime:

import org.slf4j.MDC // ... MDC.get("name-parameter")
Last modified: 28 June 2021