英文:
Log all queries that mgo fire in the application
问题
如何使用mgo在标准输出中记录每个查询?
我设置了日志记录器,但它显示了很多信息,没有实际的查询。
英文:
How to log every query with mgo in standard output?
I set logger but it shows a lot of information without actual queries.
答案1
得分: 4
来自mgo作者Gustavo Niemeyer的回答:http://grokbase.com/t/gg/mgo-users/152571ky82/how-to-show-query-log#20150209zwzki7mxjfigdzuqp245wskkl4
有两种方法可以处理这个问题:
-
启用MongoDB日志记录
这与驱动程序(在这种情况下是mgo)无关,可以在shell中启用,也可以通过mgo运行相应的命令启用:
http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/
-
启用mgo日志记录
您可以通过使用标准包的log.New函数创建一个Logger,并将其提供给mgo的SetLogger函数来实现:
http://golang.org/pkg/log/#New, http://gopkg.in/mgo.v2#SetLogger
使用mgo.SetDebug来增加详细程度:
所以,如果您已经设置了Logger,请启用调试模式。
英文:
An answer from Gustavo Niemeyer, author of mgo : http://grokbase.com/t/gg/mgo-users/152571ky82/how-to-show-query-log#20150209zwzki7mxjfigdzuqp245wskkl4
> There are two ways you can handle this issue:
>
> 1. By enabling MongoDB logging
>
> This is independent from the driver (mgo in this case), and can be
> enabled in the shell or by running the respective command via mgo:
>
http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/
>
> 2. By enabling mgo logging
>
> You can do this by creating a Logger via the standard package's
> log.New function and providing it to mgo's SetLogger function:
>
http://golang.org/pkg/log/#New, http://gopkg.in/mgo.v2#SetLogger
>
> Use mgo.SetDebug to increase the verbosity:
>
http://gopkg.in/mgo.v2#SetDebug
So if you already have the Logger set, enable the debug mode.
答案2
得分: 3
我无法使用SetLogger和SetDebug使mgo记录查询。相反,我通过将查询结果转换为JSON字符串,然后打印出来来解决了这个问题:
q := bson.M{}
jsonString, _ := json.Marshal(q)
fmt.Printf("mgo query: %s\n", jsonString)
如果需要调试查询,您还可以将此输出复制/粘贴到标准的Mongo客户端中。
英文:
I couldn't get mgo to log queries using SetLogger and SetDebug. Instead, I solved this by marshaling to json string and then printing:
q = bson.M{}
jsonString, _ := json.Marshal(q)
fmt.Printf("mgo query: %s\n", jsonString)
You can also copy/paste the output of this into a standard mongo client if you need to debug a query.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论