log all queries that mongoose fire in the application

前端 未结 4 1991
忘了有多久
忘了有多久 2020-12-04 09:52

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

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 10:01

    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
        });
    });
    

提交回复
热议问题