Ktor 1.6.7 Help

Logging

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

Add Logback dependencies

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

implementation "ch.qos.logback:logback-classic:$logback_version"
implementation("ch.qos.logback:logback-classic:$logback_version")
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback_version}</version> </dependency>

Configure Logback

To configure Logback, you need to put a logback.xml file in the root of the classpath (for example, in src/main/resources). The example below shows a sample Logback configuration with the STDOUT appender, which outputs logs to the console.

<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="io.netty" level="INFO"/> </configuration>

If you want to output logs to a file, you can use the FILE appender.

<configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>testFile.log</file> <append>true</append> <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="FILE"/> </root> <logger name="io.netty" level="INFO"/> </configuration>

Learn more about configuring Logback from Logback configuration.

Access the logger

The Logger instance is represented by a class that implements the Logger interface. You can access the Logger instance inside the Application using the Application.log property. For example, the code snippet below shows how to add a message to a log inside the module.

fun Application.module(testing: Boolean = false) { log.info("Hello from module!") }

You can also access the Logger from ApplicationCall using the call.application.environment.log property.

routing { get("/api/v1") { call.application.environment.log.info("Hello from /api/v1!") } }

To enable logging of client requests, you can use the CallLogging plugin.

Last modified: 09 September 2021