Overview
In this guide, you will learn how to:
Set up a logger by using the Simple Logging Facade For Java (SLF4J)
Configure the log level of your logger
This guide shows how to record events in the driver. To learn how to use information about the activity of the driver in code, see the Monitoring guide.
Important
Project Reactor Library
This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation.
Set Up a Logger
This section gives background on the dependencies necessary to set up a logger and provides an example logger setup.
Background
The Java Reactive Streams driver uses the Simple Logging Facade For Java (SLF4J). SLF4J allows you to specify your logging framework of choice at deployment time. For more information about SLF4J, see the SLF4J documentation.
Setting up a logger is optional. When you start your application, the Java Reactive Streams driver looks for the slf4j-api artifact in your classpath. If the driver can't find the slf4j-api artifact, the driver uses java.util.logging to log 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 in your project:
The
slf4j-apiartifactA logging framework
A binding
Note
For the most popular logging frameworks, there is often a single binding artifact that lists the slf4j-api and the logging framework as dependencies. This means that you can set up a logger by adding one artifact to your project's dependency list. You will see this in the example below.
A binding is a piece of code that connects the slf4j-api artifact with a logging framework. Select a tab to learn how to set up and configure your logger:
Example - Set Up
This example shows how to set up your Logback logger.
Tip
Dependency Versions
The following versions are illustrative rather than a source of truth. Check the official documentation for SLF4J and your logging framework of choice for guaranteed up-to-date version information.
Select the Maven or Gradle instructions based on your build tool:
Maven
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>
Gradle
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 use the following code to retrieve a document:
MongoClient mongoClient = MongoClients.create("<connection URI>"); MongoDatabase database = mongoClient.getDatabase("<database>"); MongoCollection<Document> collection = database.getCollection("<collection>"); Flux.from(collection.find()).blockFirst();
You should see output 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 example in the Configure Your Logger section of this page.
For more information about Logback, see the Logback manual.
Configure Your Logger
To configure your logger, you must use the configuration system of the logging framework bound to SLF4J.
The following example shows how you can use your logging framework's configuration system to set your logger's log level.
A logger's log level specifies a lower bound for how urgent a message must be for the logger to output that message.
Example - Configure
This example shows how to configure your logger's log level to INFO.
Specify Logback configurations in a file named logback.xml. You don't need to create your logback.xml file in a specific location, but you must be able to access it from your classpath.
The Logback framework defines the following log levels, ordered from most urgent to least urgent:
ERROR
WARN
INFO
DEBUG
TRACE
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:
MongoClient mongoClient = MongoClients.create("<connection URI>"); MongoDatabase database = mongoClient.getDatabase("<database>"); MongoCollection<Document> collection = database.getCollection("<collection>"); Flux.from(collection.find()).blockFirst();
You should see 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>
For more information about configuring Logback, see the Logback Manual.
Logger Names
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".
For a concrete example, this is what a logger hierarchy looks like in code:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; ... Logger logger_parent = LoggerFactory.getLogger("parent"); Logger logger_child = LoggerFactory.getLogger("parent.child");
A logger inherits the properties of its ancestor logger and can define its own. You can think of this as similar to class inheritance in Java.
The Java Reactive Streams driver defines the following logger names to organize different logging events in the driver:
org.mongodb.driver.authenticator: Authenticationorg.mongodb.driver.client: Events related toMongoClientinstancesorg.mongodb.driver.cluster: Monitoring of MongoDB deploymentsorg.mongodb.driver.connection: Connections and connection poolsorg.mongodb.driver.connection.tls: TLS/SSLorg.mongodb.driver.operation: Operations, including logging related to automatic retriesorg.mongodb.driver.protocol.command: Commands sent to and replies received from MongoDB deploymentsorg.mongodb.driver.uri: Connection string parsingorg.mongodb.driver.management: Java Management Extensions (JMX)
Example - Names
This example shows how to change the log level for a specific driver logger. The example sets the root logger to OFF and the org.mongodb.driver.connection logger to INFO. This causes the application to log only messages related to connecting to a MongoDB instance.
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:
MongoClient mongoClient = MongoClients.create("<connection URI>"); MongoDatabase database = mongoClient.getDatabase("<database>"); MongoCollection<Document> collection = database.getCollection("<collection>"); Flux.from(collection.find()).blockFirst();
You should see 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>
For more information about configuring Logback, see the official Logback configuration guide.
Example - Set Up
This example shows how to set up your Log4j logger.
Tip
Dependency Versions
The following versions are illustrative rather than a source of truth. Check the official documentation for SLF4J and your logging framework of choice for guaranteed up-to-date version information.
Select the Maven or Gradle instructions based on your build tool:
Maven
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>
Gradle
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, use the following code to log an error:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; ... Logger logger = LoggerFactory.getLogger("MyApp"); logger.error("Logging an Error");
You should see output 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. Running standard operations in the Java Reactive Streams driver will not produce output from Log4j2 without 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.
Configure Your Logger
To configure your logger, you must use the configuration system of the logging framework bound to SLF4J.
The following example shows how you can use your logging framework's configuration system to set your logger's log level.
A logger's log level specifies a lower bound for how urgent a message must be for the logger to output that message.
Logger Names
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".
For a concrete example, this is what a logger hierarchy looks like in code:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; ... Logger logger_parent = LoggerFactory.getLogger("parent"); Logger logger_child = LoggerFactory.getLogger("parent.child");
A logger inherits the properties of its ancestor logger and can define its own. You can think of this as similar to class inheritance in Java.
The Java Reactive Streams driver defines the following logger names to organize different logging events in the driver:
org.mongodb.driver.authenticator: Authenticationorg.mongodb.driver.client: Events related toMongoClientinstancesorg.mongodb.driver.cluster: Monitoring of MongoDB deploymentsorg.mongodb.driver.connection: Connections and connection poolsorg.mongodb.driver.connection.tls: TLS/SSLorg.mongodb.driver.operation: Operations, including logging related to automatic retriesorg.mongodb.driver.protocol.command: Commands sent to and replies received from MongoDB deploymentsorg.mongodb.driver.uri: Connection string parsingorg.mongodb.driver.management: Java Management Extensions (JMX)
Example - Names
This example shows how to change the log level for a specific driver logger. The example sets the root logger to OFF and the org.mongodb.driver.connection logger to INFO. This causes the application to log only messages related to connecting to a MongoDB instance.
Insert the following code into your log4j2.xml file:
<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:
MongoClient mongoClient = MongoClients.create("<connection URI>"); MongoDatabase database = mongoClient.getDatabase("<database>"); MongoCollection<Document> collection = database.getCollection("<collection>"); Flux.from(collection.find()).blockFirst();
You should see 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>
Additional Information
For more information about configuring Log4j2, see the official Log4j2 configuration guide.
Connection Settings
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 |
|---|---|
| Sets the maximum document length, in characters, of a single log message Default: |
Example
This example names the application sending requests and specifies that the maximum number of characters for a single log message is 5000 characters.
MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyConnectionString( new ConnectionString("<connection URI>")) .applicationName("<application name>") .applyToLoggerSettings(builder -> builder.maxDocumentLength(5000)) .build()); Flux.from(mongoClient.listDatabaseNames()) .doOnNext(System.out::println) .blockLast();
You should see output that resembles the following:
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 ...
Additional Information
For more information about the connection settings described in this section, see the MongoClientSettings.Builder API documentation.