node.js 记录应用程序中猫鼬触发的所有查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18762264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
log all queries that mongoose fire in the application
提问by codeofnode
I have application using nodejs and mongodb. I have used mongoose for ODM. Now i want to log all the queries that mongoose fire during the whole application.
我有使用 nodejs 和 mongodb 的应用程序。我已经将猫鼬用于 ODM。现在我想记录整个应用程序期间猫鼬触发的所有查询。
How to log these?
如何记录这些?
回答by mr.freeze
You can enable debug mode like so:
您可以像这样启用调试模式:
mongoose.set('debug', true);
or add your own debug callback:
或添加您自己的调试回调:
mongoose.set('debug', function (coll, method, query, doc [, options]) {
//do your thing
});
This will log all executed collection methods and their arguments to the console.
这会将所有执行的收集方法及其参数记录到控制台。
回答by lesterzone
I'm using node bunyan, this is an option to debug and track queries(may help someone else)
我正在使用节点 bunyan,这是一个调试和跟踪查询的选项(可能对其他人有帮助)
function serializer(data) {
let query = JSON.stringify(data.query);
let options = JSON.stringify(data.options || {});
return `db.${data.coll}.${data.method}(${query}, ${options});`;
}
let log = bunyan.createLogger({
name: 'AppName',
src: false,
serializers: {
// ...
dbQuery: querySerializer
// ...
},
// ...
});
mongoose.set('debug', function(coll, method, query, doc, options) {
let set = {
coll: coll,
method: method,
query: query,
doc: doc,
options: options
};
log.info({
dbQuery: set
});
});
回答by Vithal Reddy
You can use the following format:
您可以使用以下格式:
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
or any other logger of your choice:
或您选择的任何其他记录器:
mongoose.set("debug", (collectionName, method, query, doc) => {
logger(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
回答by Zilvinas
You can also set debug logger parameters:
您还可以设置调试记录器参数:
node index.js DEBUG=mquery
but this will only log queries, not insert or update statements.
但这只会记录查询,而不是插入或更新语句。

