记录应用程序中mgo发出的所有查询日志。

huangapple go评论79阅读模式
英文:

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

有两种方法可以处理这个问题:

  1. 启用MongoDB日志记录

    这与驱动程序(在这种情况下是mgo)无关,可以在shell中启用,也可以通过mgo运行相应的命令启用:

    http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/

  2. 启用mgo日志记录

    您可以通过使用标准包的log.New函数创建一个Logger,并将其提供给mgo的SetLogger函数来实现:

    http://golang.org/pkg/log/#New, http://gopkg.in/mgo.v2#SetLogger

    使用mgo.SetDebug来增加详细程度:

    http://gopkg.in/mgo.v2#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.

huangapple
  • 本文由 发表于 2015年8月30日 01:18:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/32288754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定