The Lone C++ Coder's Blog

The Lone C++ Coder's Blog

The continued diary of an experienced C++ programmer. Thoughts on C++ and other languages I play with, Emacs, functional, non functional and sometimes non-functioning programming.

Timo Geusch

2-Minute Read

I will show you how to enable logging in the MongoDB Java driver and also how to set and change the log level. The official mongoDB Java driver uses java.util.logging as its default logging framework or sl4j if the latter is present. It can be very useful to enable logging in the MongoDB drivers to trace how the driver is interacting with the database.

There are two steps you need to take to enable logging in the MongoDB Java driver. First, you need to create or update the configuration file for the java.util.logging subsystem. The example configuration file shown below sets up the log system with the following settings:

  • It sets the default overall logging level to Level.WARNING
  • It sets the MongoDB Java driver logging level to Level.FINER
  • It enables the ConsoleHandler logging at Level.FINEST.

It is important to configure the log output handler’s minimum level to the level you expect to see log output at. If you don’t, the logging system will suppress the output below the minimum level the handlers are set to. That would defeat the purpose of enabling logging in the MongoDB Java driver in the first place!

For a quick and dirty debugging session I tend to use the ConsoleHandler. You will want to log to a file or syslog if you expect lots of output from either the driver or the application.

Here is the example configuration file:

handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = WARNING
org.mongodb.driver.level = FINER
java.util.logging.ConsoleHandler.level = FINEST

After creating or updating the configuration file, you need to tell java.util.logging where to find it. You do this by passing the command line parameter java.util.logging.config.file to your program. For example, if you are trying to run your project from maven and your configuration file is called logging.properties, your command line looks like this:

mvn exec:java "-Djava.util.logging.config.file=logging.properties"

Once you’re up and running you will see the driver interact with the database. Season to taste, sorry, adjust the logging level to your requirements - I tend to start with INFO and work my way down from there.

Disclaimer: I work for mongoDB as a consulting engineer, but this is my personal blog. All opinions expressed herein are mine and mine alone. They don’t reflect the opinion of employers past, present or future and don’t constitute endorsements by them either.

Recent Posts

Categories

About

A developer's journey. Still trying to figure out this software thing after several decades.