118

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?

codeofnode
  • 18,169
  • 29
  • 85
  • 142

5 Answers5

249

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.

mr.freeze
  • 13,731
  • 5
  • 36
  • 42
  • 4
    how does mongoose format the log. IE I would like to use the second option to let winston log. I like the format mongoose logs and I would format my log w/ winston the same way. – lostintranslation May 21 '14 at 02:38
20

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);
});
Vithal Reddy
  • 392
  • 1
  • 6
  • 12
  • 3
    Nice. But how to add color to only value like mongoose debug default –  coinhndp May 28 '19 at 13:24
  • you can use chalk npm module to color, whichever values you want to colorize `log(\` CPU: ${chalk.red('90%')} RAM: ${chalk.green('40%')} DISK: ${chalk.yellow('70%')} \`);` – Vithal Reddy May 29 '19 at 14:36
12

I'm using node bunyan, this is an option to debug and track queries(may help someone else)

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
    });
});
lesterzone
  • 233
  • 3
  • 6
4

You can also set debug logger parameters:

node index.js DEBUG=mquery

but this will only log queries, not insert or update statements.

Zilvinas
  • 5,518
  • 3
  • 26
  • 26
0

Install winston and winston-mongodb

$ npm install winston winston-mongodb
const winston = require("winston");
const { MongoDB } = require("winston-mongodb");

//  To save the logs in database
const logger = winston.createLogger({
    level: "info",
    // format: winston.format.json(),
    transports: [
        new MongoDB({
            db: process.env.MONGO_URL,
            options: {
                useUnifiedTopology: true,
                useNewUrlParser: true,
            },
        }),
     ],
});

Use logger.info() method to save the logs in mongodb

//Example
var data = "string";

logger.info(data);