Hence, in critical environments such as databases, keeping a record of the commands executed on the server can be beneficial in tracing where an error occurred and how to revert it.
In this article, we will learn how to enable the MongoDB server to log all the commands executed on the server.
MongoDB Fetch Current Log Level
We need to modify the logging level to enable or disable the logging of queries in the MongoDB server. The log level defines what information is and how it is logged into the server.
It’s good to know the current status before increasing or decreasing the log level. This will allow you to revert to its default log level.
In MongoDB, we can use the db.getProfilingStatus() command to get the current log level in a given database.
Start by logging into the MongoDB Shell:
Once logged in, switch to the database in which you wish to manage the log level. In our example, we will use ‘cinema’ database:
db.getProfilingStatus()
< { was: 0, slowms: 100, sampleRate: 1, ok: 1 }
The command should return the current log level defined in the was key. For example, in the output above, we can see the current log level of the database is set to 0.
MongoDB Log All Queries
We need to increase the log level to 2 to allow MongoDB to log all the queries in a given database.
We can accomplish this by using the db.SetProfilingLevel() command. The function accepts the target level we wish to set as the parameter.
https://www.mongodb.com/docs/manual/reference/method/db.setProfilingLevel/
Setting the log level 2 collects all the data of the operations executed in the database and logs them.
We can run the command as:
< { was: 0, slowms: 100, sampleRate: 1, ok: 1 }
The command will return information as:
- was – shows the previous level
- slowms – represents the previous slowms value
- sampleRate – defines the prior sampleRate value
Finally, we can confirm the new log level with the getProfilingStatus() command as shown:
< { was: 2, slowms: 100, sampleRate: 1, ok: 1 }
Here, we can see the current log level is set to 2.
Once updated, you can check the MongoDB log file for the created entries. Check mongodb.log or mongod.log.
Conclusion
In this post, you learned how to view the current log level of a MongoDB database. You also learned how to use the setProfilingLevel command to change the current log level of a given database. For example, setting the log level to 2 allows MongoDB to log all operations in the database.