For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Logging

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

This guide shows how to record events in the driver. If you would like to learn how to use information about the activity of the driver in code, see the Monitoring guide.

This section explains the dependencies necessary to set up a logger and provides an example logger setup.

The MongoDB Scala driver uses the Simple Logging Facade For Java (SLF4J). You can specify a logging framework at deployment time when you use SLF4J. Setting up a logger is optional in the Scala driver.

When you start your application, the MongoDB Scala driver looks for the slf4j-api artifact in your classpath. If the driver can't find the slf4j-api artifact, it logs the following warning and disables all further logging:

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

To set up a logger, you must include the following components in your project:

  • The slf4j-api artifact

  • A logging framework

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

The following example shows how to bind the slf4j-api artifact to your chosen logging framework.

Select the Logback or Log4j2 tab to set up your chosen logging framework and see corresponding code examples:

To use Logback, add the following lines to your project's build.sbt file. These lines include the slf4j-api artifact, the logging framework, and the binding.

libraryDependencies += "org.slf4j" % "slf4j-api" % "2.0.13"
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.5.6"

To test your Logback setup, add the following code to your project's Main.scala file. The code connects to your MongoDB deployment and retrieves a document. After you add the code, use sbt run to run your application in the terminal rather than the IDE.

val mongoClient = MongoClient("<connection string>")
val database: MongoDatabase = mongoClient.getDatabase("<database>")
val collection: MongoCollection[Document] = database.getCollection("<collection>")
collection.find().first().printHeadResult()
...
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. The DEBUG level records detailed diagnostic messages intended for troubleshooting, such as opened connections and the commands the driver sends to and receives from MongoDB. To learn how to change your Logback logger's log level, see the example in the Configure Your Logger section of this page.

For more information about Logback, see the Logback manual.

To use Log4j2, add the following lines to your project's build.sbt file. These lines include the slf4j-api artifact, the logging framework, and the binding.

libraryDependencies += "org.slf4j" % "slf4j-api" % "2.0.13"
libraryDependencies += "org.apache.logging.log4j" % "log4j-slf4j2-impl" % "2.24.3"
libraryDependencies += "org.apache.logging.log4j" % "log4j-core" % "2.24.3"

To test your Log4j2 setup, add the following code to your project's Main.scala file. The code logs an error message. After you add the code, use sbt run to run your application in the terminal rather than the IDE.

import org.slf4j.Logger
import org.slf4j.LoggerFactory
val logger: Logger = LoggerFactory.getLogger("MyApp")
logger.error("Logging an Error")
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 MongoDB Scala driver will not produce output from Log4j2 without log level configuration. To learn how to change your Log4j2 logger's log level, see the example in the Configure Your Logger section of this page.

For more information about Log4j2, see the Log4j2 manual.

For more information about SLF4J, see the SLF4J documentation.

To configure your logger, you must use the configuration system of the logging framework you bound to SLF4J.

A log level specifies how urgent a message must be for the logger to output that message. The following example shows how to use each logging framework's configuration system to set the log level to INFO. Select the Logback or Log4j2 tab to see corresponding code for each approach:

Logback reads its configuration from a file named logback.xml on your classpath. This file doesn't exist by default, so you must create it. You can place logback.xml anywhere in your Scala project, as long as it's accessible from your classpath.

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

  • ERROR

  • WARN

  • INFO

  • DEBUG

  • TRACE

To learn more about what each log level means, see Effective Level in the Logback documentation.

Insert the following code into your logback.xml file:

<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 by using the sbt run command rather than your IDE:

val mongoClient = MongoClient("<connection string>")
val database: MongoDatabase = mongoClient.getDatabase("<database>")
val collection: MongoCollection[Document] = database.getCollection("<collection>")
collection.find().first().printHeadResult()
...
1317 [cluster-<your cluster id>-<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>

For more information about configuring Logback, see the Logback Manual.

Log4j2 reads its configuration from a file named log4j2.xml on your classpath. This file doesn't exist by default, so you must create it. You can place log4j2.xml anywhere in your Scala project, as long as it's accessible from your classpath.

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

  • FATAL

  • ERROR

  • WARN

  • INFO

  • DEBUG

  • TRACE

  • ALL

To learn more about what each log level means, see Custom Log Levels in the Log4j2 documentation.

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 by using the sbt run command rather than your IDE:

val mongoClient = MongoClient("<connection string>")
val database: MongoDatabase = mongoClient.getDatabase("<database>")
val collection: MongoCollection[Document] = database.getCollection("<collection>")
collection.find().first().printHeadResult()
...
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>

For more information on configuring Log4j2, see the Log4j2 configuration guide in the Log4j2 documentation.

Logging frameworks use hierarchical logger names to organize logging events. 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, the grandparent logger is an ancestor of the grandparent.parent logger, which is an ancestor of the grandparent.parent.child logger.

The following code creates a parent logger and a parent.child logger, in which the parent logger is an ancestor of the parent.child logger:

import org.slf4j.Logger
import org.slf4j.LoggerFactory
val loggerParent: Logger = LoggerFactory.getLogger("parent")
val loggerChild: Logger = LoggerFactory.getLogger("parent.child")

A logger hierarchy is similar to a class hierarchy in Scala: a logger inherits the properties of its ancestor logger and can also define its own.

The Scala driver includes the following default logger names:

  • org.mongodb.driver.authenticator: Authentication

  • org.mongodb.driver.client: MongoClient instances

  • org.mongodb.driver.cluster: MongoDB deployment monitoring

  • org.mongodb.driver.connection: Connections and connection pools

  • org.mongodb.driver.connection.tls: TLS/SSL

  • org.mongodb.driver.operation: Operations, including automatic retries

  • org.mongodb.driver.protocol: Commands and replies exchanged with MongoDB deployments

  • org.mongodb.driver.uri: Connection string parsing

  • org.mongodb.driver.management: Java Management Extensions (JMX)

The following example shows how to set the root logger configuration to OFF and the org.mongodb.driver.connection logger configuration to INFO, so that the application logs only messages related to connecting to a MongoDB deployment.

Select the Logback or Log4j2 tab to see example configuration and output for the corresponding framework:

Insert the following code into your logback.xml file:

<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 by using the sbt run command rather than your IDE:

val mongoClient = MongoClient("<connection string>")
val database: MongoDatabase = mongoClient.getDatabase("<database>")
val collection: MongoCollection[Document] = database.getCollection("<collection>")
collection.find().first().printHeadResult()
...
829 [cluster-<your cluster id>-<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>

For more information about configuring Logback, see the official Logback configuration guide.

Insert the following code into your log4j2.xml file:

<?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 by using the sbt run command rather than your IDE:

val mongoClient = MongoClient("<connection string>")
val database: MongoDatabase = mongoClient.getDatabase("<database>")
val collection: MongoCollection[Document] = database.getCollection("<collection>")
collection.find().first().printHeadResult()
...
15:40:23.005 [cluster-<your cluster id>-<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>

For more information about configuring Log4j2, see the official Log4j2 configuration guide.

You can apply logging settings to your MongoClient instance by using the applyToLoggerSettings() and applicationName() methods.

The following table describes the methods that you can chain to your logger settings to modify the logging behavior:

Method
Description

maxDocumentLength()

Sets the maximum document length, in characters, of a single log message

Default: 1000

The following example names the application sending requests and specifies 5000 characters as the maximum log message length. Run the example by using the sbt run command rather than your IDE.

val mongoClient = MongoClient(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<your connection string>"))
.applicationName("<application name>")
.applyToLoggerSettings(builder =>
builder.maxDocumentLength(5000))
.build())
01:20:38.782 [main] INFO org.mongodb.driver.client -- MongoClient with
metadata {"application": {"name": "<application name>"}, ...,
loggerSettings=LoggerSettings{maxDocumentLength=5000}, ... timeoutMS=null}
...
01:20:41.022 [main] DEBUG org.mongodb.driver.protocol.command -- Command
"listDatabases" succeeded ... Command reply: {"databases": [...], ...}
01:20:41.024 [main] DEBUG org.mongodb.driver.connection -- Connection checked in: address=<address>, driver-generated ID=6
myDb
sample_airbnb
sample_analytics
...

For more information, see the MongoClientSettings.Builder API documentation.