Logging

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

Add Dependencies

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

Logging - 图1

Gradle (Groovy)

Gradle (Kotlin)

Maven

Logging - 图2

  1. implementation "ch.qos.logback:logback-classic:$logback_version"

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:

  1. routing {
  2. get("/api/v1") {
  3. call.application.environment.log.info("Hello from /api/v1!")
  4. }
  5. }

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

Call Logging

The CallLogging feature allows you to log incoming client requests.

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

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.main() {
  4. install(CallLogging)
  5. // ...
  6. }

… or a specified module:

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.module() {
  4. install(CallLogging)
  5. // ...
  6. }

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:

  1. import org.slf4j.event.Level
  2. // ...
  3. install(CallLogging) {
  4. level = Level.INFO
  5. }

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:

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

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:

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

Put Call Parameters in MDC

The CallLogging feature 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:

  1. install(CallLogging) {
  2. mdc("name-parameter") { call ->
  3. call.request.queryParameters["name"]
  4. }
  5. }

You can access the added value during an ApplicationCall lifetime:

  1. import org.slf4j.MDC
  2. // ...
  3. MDC.get("name-parameter")