Docs Menu
Docs Home
/ / /
Kotlin Sync Driver
/

Log Driver Events

In this guide, you can learn how to set up and configure a logger in the Kotlin Sync driver.

This guide shows how to record events in the driver. If you want to learn how to use information about the activity of the driver in code, see the Monitor Application Events guide.

The Kotlin Sync driver uses Simple Logging Facade For Java (SLF4J) to allow you to specify your logging framework of choice. For more information about SLF4J, see the SLF4J documentation.

Setting up a logger is optional. To set up a logger, you must include the following in your project:

  • The slf4j-api artifact in your classpath

  • A logging framework

  • A binding that connects the slf4j-api artifact to a logging framework

If the driver can't find the slf4j-api artifact in your classpath, the driver outputs the following warning and disables all further logging:

WARNING: SLF4J not found on the classpath. Logging is disabled for the 'org.mongodb.driver' component

The following example shows how to set up a logger. Select the Logback or Log4j2 tab to see the corresponding syntax:

Select the Maven or Gradle tab to learn about how to set up Logback with your project's dependency management tool:

Add the following dependency to your pom.xml file.

<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
</dependencies>

Add the following dependency to your build.gradle file.

dependencies {
implementation 'ch.qos.logback:logback-classic:1.2.11'
}

Once you have included the preceding dependency, connect to your MongoDB instance and retrieve a document with the following code:

val mongoClient = MongoClient.create(<connection uri>);
val database = mongoClient.getDatabase(<database>);
val collection = database.getCollection<Document>(<collection>);
collection.find().first();

The preceding code will ouput a message that resembles the following:

...
12:14:55.853 [main] DEBUG org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:3}] to <MongoDB hostname>
12:14:55.861 [main] DEBUG org.mongodb.driver.protocol.command - Command "find" started on database <database> using a connection with driver-generated ID 3 and server-generated ID 3 to <MongoDB hostname>. The request ID is 5. Command: {"find": "<collection>", "filter": {}, "limit": 1, "singleBatch": true, "$db": "<database>", "lsid": {"id": {"$binary": {"base64": "<_id>", "subType": "04"}}}, "$readPreference": {"mode": "primaryPreferred"}}
12:14:55.864 [main] DEBUG org.mongodb.driver.protocol.command - Command "find" succeeded in 4.34 ms using a connection with driver-generated ID 3 and server-generated ID 3 to <MongoDB hostname. The request ID is 5. Command reply: {"cursor": {"id": 0, "ns": "<database>.<collection>", "firstBatch": []}, "ok": 1.0, "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1673778535, "i": 1}}, "signature": {"hash": {"$binary": {"base64": "<_id>", "subType": "00"}}, "keyId": 0}}, "operationTime": {"$timestamp": {"t": 1673778535, "i": 1}}}

Note

Default Log Level

The default log level of Logback is DEBUG. To learn how to change your Logback logger's log level, see the Configure Log Level section of this page.

Select the Maven or Gradle tab to learn about how to set up Log4j2 with your project's dependency management tool.

Add the following dependency to your pom.xml file.

<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>

Add the following dependency to your build.gradle file.

dependencies {
implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.17.1'
}

Once you have included the preceding dependency, log an error by using the following code:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
val logger = LoggerFactory.getLogger("MyApp");
logger.error("Logging an Error");

The preceding code will ouput a message that resembles the following:

12:35:00.438 [main] ERROR <my package path> - Logging an Error

Note

Default Log Level

The default log level of Log4J2 is ERROR. This means that running standard operations in the Kotlin Sync driver will not produce output from Log4J2 without configuration. To learn how to change your Log4J2 logger's log level, see the Configure Log Level section of this page.

You can configure the log level of your logger by using the configuration system of the logging framework bound to SLF4J. The log level specifies a lower bound for how urgent a message must be for the logger to output that message.

The following example configures the log level to INFO. Select the Logback or Log4j2 tab to see the corresponding syntax:

Specify Logback configurations in a file named logback.xml. You must be able to access this file from your classpath.

The Logback framework defines the following log levels ordered from most urgent to least urgent:

  • ERROR

  • WARN

  • INFO

  • DEBUG

  • TRACE

Set your logback.xml file to the following:

<configuration>
<appender name="CONSOLE"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%-4relative [%thread] %-5level %logger{30} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

To test that your logger configuration was successful, run the following code:

val mongoClient = MongoClient.create(<connection uri>);
val database = mongoClient.getDatabase(<database>);
val collection = database.getCollection<Document>(<collection>);
collection.find().first();

This code produces output that resembles the following:

...
1317 [cluster-ClusterId{value='<your cluster id>', description='null'}-<your connection uri>] INFO org.mongodb.driver.cluster - Discovered replica set primary <your connection uri>
1568 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<server value>}] to <your connection uri>

Specify Log4j2 configurations in a file named log4j2.xml. You must be able to access this file from your classpath.

The Log4j2 framework defines the following log levels, ordered from most urgent to least urgent:

  • FATAL

  • ERROR

  • WARN

  • INFO

  • DEBUG

  • TRACE

  • ALL

Set your log4j2.xml file to the following:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

To test that your logger configuration was successful, run the following code:

val mongoClient = MongoClient.create(<connection uri>);
val database = mongoClient.getDatabase(<database>);
val collection = database.getCollection<Document>(<collection>);
collection.find().first();

This code produces output that resembles the following:

...
10:14:57.633 [cluster-ClusterId{value=<your cluster id>, description='null'}-<your connection uri>] INFO org.mongodb.driver.cluster - Discovered replica set primary <your connection uri>
10:14:57.790 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>

Your logger uses logger names to help organize different logging events. Logger names are strings that form a hierarchy. A logger is an ancestor of another logger if its name followed by a "." is a prefix of the other logger's name. For example, "grandparent" is an ancestor of "grandparent.parent", which is an ancestor of "grandparent.parent.child". A logger inherits the properties of its ancestor logger and can also define its own properties.

The Kotlin Sync driver defines the following logger names to organize different logging events:

Logger Name
Description

org.mongodb.driver.authenticator

Logs authentication events

org.mongodb.driver.client

Logs events related to MongoClient instances

org.mongodb.driver.cluster

Logs events related to monitoring of MongoDB deployments

org.mongodb.driver.connection

Logs connections and connection pools

org.mongodb.driver.connection.tls

Logs TLS events

org.mongodb.driver.operation

Logs operations, including logging related to automatic retries

org.mongodb.driver.protocol

Logs commands sent to and replies received from MongoDB deployments

org.mongodb.driver.uri

Logs connection string parsing events

org.mongodb.driver.management

Logs Java Management Extensions (JMX) events

The following example disables the root logger and sets the log level for the org.mongodb.driver.connection logger to DEBUG. This will cause the driver to log messages only related to connections and connection pools at the DEBUG level or higher. Select the Logback or Log4j2 tab to see the corresponding syntax:

Set your logback.xml file to the following:

<configuration>
<appender name="CONSOLE"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%-4relative [%thread] %-5level %logger{30} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.mongodb.driver.connection" level="INFO" additivity="true"/>
<root level="OFF">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

To test that your logger configuration was successful, run the following code.

val mongoClient = MongoClient.create(<connection uri>);
val database = mongoClient.getDatabase(<database>);
val collection = database.getCollection<Document>(<collection>);
collection.find().first();

This code produces output that resembles the following.

...
829 [cluster-rtt-ClusterId{value='<some value>', description='null'}-<your connection URI>] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:2, serverValue:<your server value>}] to <your connection uri>
977 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>

Set your log4j2.xml file to the following:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.mongodb.driver.connection" level="INFO"/>
<Root level="OFF">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

To test that your logger configuration was successful, run the following code.

val mongoClient = MongoClient.create(<connection uri>);
val database = mongoClient.getDatabase(<database>);
val collection = database.getCollection<Document>(<collection>);
collection.find().first();

This code produces output that resembles the following:

...
15:40:23.005 [cluster-ClusterId{value='<some value>', description='null'}-<your connection uri>] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:<your server value>}] to <your connection uri>
15:40:23.159 [main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:7, serverValue:<your server value>}] to <your connection uri>

To learn more about MongoDB's logging capabilities, see Log Messages in the MongoDB Server manual.

For complete information about the logging frameworks discussed in this guide, see the following external documentation:

Back

Logging and Monitoring

On this page