log all queries that mongoose fire in the application

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.

How to log these?

71740 次浏览

您可以像这样启用调试模式:

mongoose.set('debug', true);

或者添加自己的调试回调:

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.

我使用的是节点 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
});
});

还可以设置调试日志记录器参数:

node index.js DEBUG=mquery

但这只会记录 查询,而不会插入或更新语句。

You can use the following format:

mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});

或者其他任何你选择的记录器:

mongoose.set("debug", (collectionName, method, query, doc) => {
logger(`${collectionName}.${method}`, JSON.stringify(query), doc);
});