Skip to content

Latest commit

 

History

History
70 lines (51 loc) · 2.89 KB

call-logging.md

File metadata and controls

70 lines (51 loc) · 2.89 KB

Required dependencies: io.ktor:%artifact_name%

Ktor provides the capability to log application events using the SLF4J library. You can learn about general logging configuration from the topic.

The %plugin_name% plugin allows you to log incoming client requests.

Add dependencies {id="add_dependencies"}

Install %plugin_name% {id="install_plugin"}

Configure logging settings {id="configure"}

You can configure %plugin_name% 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 CallLoggingConfig.

Set the logging level {id="logging_level"}

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

{src="snippets/logging/src/main/kotlin/com/example/Application.kt" lines="14-15,25"}

Filter log requests {id="filter"}

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:

{src="snippets/logging/src/main/kotlin/com/example/Application.kt" lines="14,16-18,25"}

Customize a log message format {id="format"}

By using the format function, you can put any data related to a request/response into a log. The example below shows how to log a response status, a request HTTP method, and the User-Agent header value for each request.

{src="snippets/logging/src/main/kotlin/com/example/Application.kt" lines="14,19-25"}

You can find the full example here: logging.

Put call parameters in MDC {id="mdc"}

The %plugin_name% 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")