Log service name with slow queries in MongoDB — Spring data & Java

Hamza Sabljakovic
2 min readMay 25, 2022
Photo by Campaign Creators on Unsplash

In many systems, no matter how well written, occasionally, a query will gradually slow down and be marked as a slow query. By default, the Mongo database logs all queries that exceed the execution time of over 100 ms. The log line will look something like this:

The log line contains many useful properties such as ns (namespace), which is the database and collection name, the execution plan, how long did the query take, etc. This information will be enough to track down the service responsible for the query in many cases. For example, if you are familiar with the system code or the system architecture follows the database per service pattern, finding the service in question is straightforward.

However, if multiple services are querying the same database or if you are responsible for system operations and need to contact the team responsible for the problematic service there is an easier way that removes all the guesswork. The mongo driver has an additional property that can be set to be logged with every log.

There are different ways to set the mentioned property but the one we are going to showcase is to set it as a part of the URI (connection string). Besides, the fact that we are using a connection string property instead of language/driver specific config there is a high chance the same solution can be applied to a number of different languages (as stated in the MongoDB documentation, not all drivers support appName property).

mongodb://localhost:27017/development?appName=YOUR_SERVICE_NAME_GOES_HERE

If you are using spring data MongoDB, set it in the application properties files such as:

spring.data.mongodb.uri=mongodb://localhost:27017/development?appName=YOUR_SERVICE_NAME_GOES_HERE

Or as an env variable:

SPRING_DATA_MONGODB_URI=mongodb://localhost:27017/development?appName=YOUR_SERVICE_NAME_GOES_HERE

Once you are done, all slow logs produced by the service using the new updated URI (connection string) will include appName. See line number 13 in the log example bellow.

--

--