Log the client requests

You might want to log client requests: and the Call Logging feature does just that.It uses the ApplicationEnvironment.log (LoggerFactory.getLogger("Application"))that uses slf4j so you can easily configure the output. For more informationon logging in Ktor, please check the logging in the ktor page.

This feature is defined in the class io.ktor.features.CallLogging and no additional artifacts are required.

Basic usage

The basic unconfigured feature logs every request using the level TRACE:

  1. install(CallLogging)

Configuring

This feature allows you to configure the log level and filtering the requests that are being logged:

  1. install(CallLogging) {
  2. level = Level.INFO
  3. filter { call -> call.request.path().startsWith("/section1") }
  4. filter { call -> call.request.path().startsWith("/section2") }
  5. // ...
  6. }

The filter method keeps a whitelist list of filters. If no filters are defined,everything is logged. And if there are filters, if any of them returns true,the call will be logged.

In the example, it will log both: /section1/ and /section2/ requests.

MDC

The CallLogging feature supports MDC (Mapped Diagnostic Context) from slf4jto associate information as part of the request.

When installing the CallLogging, you can configure a parameter to associate to the request with the mdc method.This method requires a key name, and a function provider. The context would be associated(and the providers will be called) as part of the Monitoring pipeline phase.

  1. install(CallLogging) {
  2. mdc(name) { // call: ApplicationCall ->
  3. "value"
  4. }
  5. // ...
  6. }

MDC works by using ThreadLocals, while Ktor uses coroutines that are not bound to a specific Thread.This feature uses internally the kotlinx.coroutines ThreadContextElementto address it.