如何使用Mongo Java驱动程序记录实际查询到MongoDB

10

我想查看Mongo Java驱动程序产生的查询,但我无法做到。

根据官方文档提供的信息,我只能在日志中看到更新操作的执行情况,但我看不到该操作的查询。


请查看此答案:https://dev59.com/CloU5IYBdhLWcg3wxY8l#39721643 - Jahan Zinedine
@JahanZinedine的评论中的问题特别针对Spring Data MongoDB。 - Wit
2个回答

16

您可以将org.mongodb的日志记录级别设置为DEBUG,这样您的Java驱动程序将会输出如下详细日志:

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  

在上面的日志输出中,您可以看到客户端提交的查询的详细信息:

org.mongodb.driver.protocol.command|Sending command {find : BsonString{value='sample'}}

或者,您可以在服务器端启用分析功能...

db.setProfilingLevel(2)

...导致MongoDB分析器收集针对该数据库的全部操作数据。

分析器输出(包括客户端提交的查询)将被写入已启用分析的任何数据库中的system.profile集合中。

有关更多详细信息,请参见文档,但简要总结如下:

// turn up the logging
db.setProfilingLevel(2)

// ... run some commands

// find all profiler documents, most recent first
db.system.profile.find().sort( { ts : -1 } )

// turn down the logging
db.setProfilingLevel(0)

是的,o.g.sandbox.mongo.MongoClientTest 是我自己的测试类。我已经更新了答案以消除这种可能的混淆。我答案中显示的其他日志事件确实包括 MongoDB find 命令的详细信息,例如 Sending command {find : BsonString{value='sample'}} - glytching
但我想要准确的查询日志,就像你在MongoClientTest类中所拥有的那样。 - Deplake
我明白了,谢谢。我只是想要类似于Java日志中的system.profile,而不是在数据库中。 - Deplake
对我来说,使用 org.mongodb 而不是 com.mongodb 是有效的。 - Mohamed Gara
本答案中显示的日志仍不如文档中详细。升级您的驱动程序版本以查看更多详细信息。 - Wit
显示剩余3条评论

1
如果您正在使用Spring Boot 1.5.x(我在1.5.19上),则需要将org.mongodb:mongodb-driver的版本覆盖至少到3.7.0才能在日志中获取其他信息。
有关更多详情,请参见此工单:https://jira.mongodb.org/browse/JAVA-2698

在我的情况下,我还需要添加与org.mongodb:mongo-java-driver相同版本的依赖项,以便像日志记录文档中那样查看详细日志。 - Wit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接