Logging in Ktor

Ktor uses SLF4J for logging.

SLF4J Providers

If you don’t add a logging provider, you will see thefollowing message when you run your application:

  1. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
  2. SLF4J: Defaulting to no-operation (NOP) logger implementation
  3. SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

We can set up logging to remove these warning messages and geta better idea of what is happening with the app by adding a provider.

Providers use Java’s ServiceLoader mechanism,and so are discovered and added automatically without having to do anythingelse by code.

Logback provider

You can use logback,which is the successor of log4j, as a SLF4J provider:

Gradle’s build.gradle or build.gradle.kts:

  1. compile("ch.qos.logback:logback-classic:1.2.3")

Mavens’s pom.xml:

  1. <dependency>
  2. <groupId>ch.qos.logback</groupId>
  3. <artifactId>logback-classic</artifactId>
  4. <version>1.2.3</version>
  5. </dependency>

Once added, run the app, and you should now see the logging messagesin the Run pane of IDEA. However, these logging messages are not ashelpful as they could be.

Configuring the Logback provider

If the default logging is not enough, you can put a logback.xml or logback-test.xml (that has higher priority) file in your src/main/resources folderto adjust the logging if it is not useful to you. For example:

logback.xml

  1. <configuration>
  2. <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  3. <encoder>
  4. <pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  5. </encoder>
  6. </appender>
  7. <root level="trace">
  8. <appender-ref ref="STDOUT"/>
  9. </root>
  10. <logger name="org.eclipse.jetty" level="INFO"/>
  11. <logger name="io.netty" level="INFO"/>
  12. </configuration>

After it is added, if you stop your app, and run it again, after goingto localhost:8080 in your browser, you should see a log message now in the IDEA run pane, something like:

  1. 2017-05-29 23:08:12.926 [nettyCallPool-4-1] TRACE ktor.application - 200 OK: GET - /

You can install the Call Logging feature to catch and log requests.

To understand how to change the logback.xml configuration fileand change the logging, see the logback manual.

Accessing the main logger

The ApplicationEnvironment interface has a log property.You can access it inside an ApplicationCall with call.application.environment.log.