How can I log actual queries to MongoDB with mongo java driver
You can set the logger level for org.mongodb
to DEBUG
and your Java driver will emit detailed logging like this:
2018-01-18 16:51:07|[main]|[NA]|INFO |org.mongodb.driver.connection|Opened connection [connectionId{localValue:2, serverValue:39}] to localhost:27017 2018-01-18 16:51:07|[main]|[NA]|DEBUG|org.mongodb.driver.protocol.insert|Inserting 1 documents into namespace stackoverflow.sample on connection [connectionId{localValue:2, serverValue:39}] to server localhost:27017 2018-01-18 16:51:07|[main]|[NA]|DEBUG|org.mongodb.driver.protocol.insert|Insert completed 2018-01-18 16:51:07|[main]|[NA]|DEBUG|org.mongodb.driver.protocol.command|Sending command {find : BsonString{value='sample'}} to database stackoverflow on connection [connectionId{localValue:2, serverValue:39}] to server localhost:27017 2018-01-18 16:51:07|[main]|[NA]|DEBUG|org.mongodb.driver.protocol.command|Command execution completed 2018-01-18 16:51:07|[main]|[NA]|DEBUG|org.mongodb.driver.protocol.command|Sending command {findandmodify : BsonString{value='sample'}} to database stackoverflow on connection [connectionId{localValue:2, serverValue:39}] to server localhost:27017 2018-01-18 16:51:07|[main]|[NA]|DEBUG|org.mongodb.driver.protocol.command|Command execution completed
In the above log output you can see the details of a query submitted by the client:
org.mongodb.driver.protocol.command|Sending command {find : BsonString{value='sample'}}
Alternatively, you can enable profiling on the server side ...
db.setProfilingLevel(2)
... causes the MongoDB profiler to collect data for all operations against that database.
The profiler output (which includes the query submitted by the client) is written to the system.profile
collection in whichever database profiling has been enabled.
More details in the docs but the short summary is:
// turn up the loggingdb.setProfilingLevel(2)// ... run some commands// find all profiler documents, most recent firstdb.system.profile.find().sort( { ts : -1 } )// turn down the loggingdb.setProfilingLevel(0)
If you're using Spring Boot 1.5.x (I'm on 1.5.19) you'll need to override the version of org.mongodb:mongodb-driver
to at least version 3.7.0 to get the additional info in the logs.
See this ticket for more details: https://jira.mongodb.org/browse/JAVA-2698