简体   繁体   中英

Log all queries using mongodb native driver for Node JS

Im relatively new to the MongoDB. At first I used mongoose, but now I decided to abandon it. Immediately I ran into the following problem: I can't understand how to print all the performed queries to the console.

In mongoose this could be done as simple as to write mongoose.set('debug', true), but how to do that using native driver?

I've read about Logger in the dcumentation, but the output seems completely unreadable for me. Is it possble to tune the output or i should just parse that somehow?

You should use the mongo's Logger class (see the official API doc ):

const connect = async () => {
    console.log("Connecting to database...");

    try {
        let client = await MongoClient.connect(uri, opts);
        console.log("Database connected.");

        Logger.setLevel("debug");
        console.log("MongoDB Logger set to DEBUG");
    } catch (e) {
        console.log("ERROR: " + e.message);
    }
};

The Logger class has multiple options (info, debug, error). They will log different types of database actions/events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM