How to Configure MongoDB Logging

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Logging is a key part of database administration, so it’s important to configure it correctly on your MongoDB deployment. Fortunately, it’s not difficult to learn how to configure MongoDB logging: If you make use of the java.util.logging package, all it takes is a bit of simple code to get your logging set up. In this article, we’ll provide step-by-step instructions for configuring MongoDB logging using java.util.logging.

Prerequisites

Before we move on to the Java code, let’s pause and review the system requirements for this task. There are only a few prerequisites that need to be taken care of:

  • First, you’ll need to make sure that both MongoDB and the MongoDB Java driver have been properly configured.

  • You’ll also need to make sure that the latest Java JDK has been properly installed and configured.

  • Last but not least, you’ll need to make sure that the MongoDB service is running.

NOTE: The MongoDB version used in this tutorial is 4.0, and the MongoDB Java Driver is 3.8.2.

What is Logging?

Logging can be defined as the process of capturing log messages during the processing of a certain program or application into a central place.

Logging enables the user to report the following log messages:

  1. Error Messages
  2. Warning Messages
  3. Info Messages

Java Logging API

  • MongoDB uses the java.util.logging package. This package includes the Logger class that provides logging capabilities.

JUL (java.util.logging) Levels

You can use different levels to control the amount of output that’s written to the logs:

LevelDescription
ALLAll messages will be logged
CONFIGStatic configuration will be logged.
FINEProviding tracing information
FINERFairly detailed message
FINESTHighly detailed message
INFOInformational message
OFFUsed to turn off logging
SEVEREIndicating serious failure
WARNINGIndicating a potential problem

Create Java function for logging messages

At this point, we’re ready to start writing the code needed to configure MongoDB logging using java.util.logging. We’ll start by creating a class called MyLogger. This class holds the code for creating the FileHandler, root logger and the formatter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MyLogger {

public static Logger logger;
// FileHandler that writes the messages in to a file
FileHandler fh;


// This functions requires a string to be passed in
// The string should be the path to the location of the log file
public Log(String file_name) throws IOException {
File f = new File(file_name);
if(!f.exists()) {
f.createNewFile();
}

fh = new FileHandler(file_name, true);

// root logger for org.mongodb.driver, this needs to import
//import com.mongodb.diagnostics.logging.Loggers;

logger = Logger.getLogger(Loggers.PREFIX);

logger.addHandler(fh);
// Each ""handler"" can be configured using a formatter
// SimpleFormatter generate messages as text
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
}
}

Executing the Java function

The Java code shown below will execute MongoDB’s logging capabilities. Here, we create another Java class called functionClass:

1
2
3
4
5
6
7
8
9
10
11
12
// sample basic query java function
// to trigger the logging, an operation is needed to be performed.
public class functionClass {

public void findDoc(){
MongoClient mongo = MongoClients.create(""mongodb://127.0.0.1:27017"");
MongoDatabase db = mongo.getDatabase(""SOME_DATABASE"");
MongoCollection<document> dbColl = db.getCollection(""SOME_COLLECTION"");

dbColl.find().first();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) {


//instantiate functionClass to access the findDoc function
functionClass sampleFunction = new functionClass();

// triggers the function findDoc() and perform operation
sampleFunction.findDoc();

// level is set to FINE for tracing information
mongoLogger.setLevel(Level.FINE);

try {
// sets the path location where the log messages will be stored
Log mylog = new Log(""/home/rommel/Documents/log.text"");

// Sets the level to FINEST
mylog.logger.setLevel(Level.FINEST);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

As a result of the above code, the file called “”log.text”” will be created in the following path:

/home/rommel/Documents/log.text.

The log messages will look like the example shown below:

1
FINE: Sending command '{ ""find"" : ""playerInfo"", ""limit"" : 1, ""singleBatch"" : true, ""$db"" : ""playerDB"", ""$readPreference"" : { ""mode"" : ""primaryPreferred"" } }' with request id 16 to database playerDB on connection [connectionId{localValue:4, serverValue:275}] to server 127.0.0.1:27017

Conclusion

When you’re managing a MongoDB deployment, you want to make sure you’re capturing enough information to debug errors and monitor activity. Configuring MongoDB logging and choosing the appropriate log level can help you achieve this goal. With the step-by-step instructions provided in this article, you can learn how to configure MongoDB logging and use that logging information to proactively monitor your system.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.