How to log Mongodb connection acquire & release time in Java

I have Spring Boot application. I am using Morphia to connect to Mongodb database. I want to log when a connection is acquired by my Java Thread & when it gets released. Our plan is to log the pattern & use ELK to check if some request is doing long running operation on DB.
Basically I am looking something similar to this article, but it is for Hibernate with MySQL.

Hello @MdDas123,

Welcome to the community!! :wave:

If I understand the question correctly, you need a way to log connection start & finish from your Java application, as per the example from the blog post you posted. Is this correct?

If yes, then if I’m not mistaken the answer would be Java-specific instead of MongoDB-specific, and the solution you’re looking for would not be unique to MongoDB’s Java driver. Having said that, if the ultimate goal is to determining long-running operations (here I assume you mean long-running MongoDB queries initiated by your Java app), then there are two ways MongoDB may be able to help you.

  • Use MongoDB logs - MongoDB maintains a running log of events, including entries such as incoming connections, commands run, and issues encountered. Generally, log messages are useful for diagnosing issues, monitoring your deployment, and tuning performance. You can also customize the profiling level by using db.setProfilingLevel(). You might find the profiling level 1 and the slowms option relevant to your use case.

  • If you are using Atlas then you can use Performance Advisor - The Performance Advisor monitors any operation with a query predicate that MongoDB considers slow and suggests new indexes to improve query performance. For the selected host and time period, the Performance Advisor evaluates up to the 20,000 most recent slow queries found in the logs. It recognizes a query as slow if it takes longer to execute than the value of slowOpThresholdMs. By default, this value is 100 milliseconds. You can change the threshold with either the profile command or the db.setProfilingLevel() mongosh method.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.