Skip to content

Latest commit

 

History

History
84 lines (56 loc) · 3.83 KB

logging.md

File metadata and controls

84 lines (56 loc) · 3.83 KB
Ktor uses SLF4J API as a facade for various logging frameworks (for example, Logback or Log4j) and allows you to log application events.

Ktor provides different means of logging your application depending on the used platform:

  • On JVM, Ktor uses SLF4J API as a facade for various logging frameworks (for example, Logback or Log4j) and allows you to log application events. To enable logging, you need to add dependencies for the desired framework and provide configuration specific for this framework.

    You can also install and configure the CallLogging plugin to log client requests.

  • For the Native server, Ktor provides a logger that prints everything to the standard output.

JVM {id="jvm"}

Add logger dependencies {id="add_dependencies"}

To enable logging, you need to include artifacts for the desired logging framework. For example, Logback requires the following dependency:

To use Log4j, you need to add the org.apache.logging.log4j:log4j-core and org.apache.logging.log4j:log4j-slf4j-impl artifacts.

Configure logger {id="configure-logger"}

To learn how to configure the selected logging framework, see its documentation, for example:

For instance, 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.

{style="block" src="snippets/logging/src/main/resources/logback.xml"}

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

{style="block" src="snippets/logging/src/main/resources/logback-fileAppender.xml"}

You can find the full example here: logging.

Native {id="native"}

To configure the logging level for the Native server, assign one of the following values to the KTOR_LOG_LEVEL environment variable when running the application:

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR

For example, the TRACE level enables route tracing that helps you determine why some routes are not being executed.

Access logger in code {id="access_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.

{src="snippets/logging/src/main/kotlin/com/example/Application.kt" include-lines="3,11-13,35"}

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

{src="snippets/logging/src/main/kotlin/com/example/Application.kt" include-lines="26-28,30,34"}