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:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
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
:
compile("ch.qos.logback:logback-classic:1.2.3")
Mavens’s pom.xml
:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</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
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
</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:
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
.