Categories
MongoDB Node.js Basics

Node.js Basics — Logging with MongoDB

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Logging

The MongoDB Node.js client has a logger built into it.

To use it, we can write:

const { MongoClient, Logger } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    Logger.setLevel("debug");
    await client.connect();
    const db = client.db("test");
    db.dropCollection('test');
    db.createCollection('test');
    const testCollection = await db.collection('test');
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection.find();
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

to call Logger.setLevel to 'debug' to see all the debug messages when the methods below it are run.

We should see a lot more messages displayed in the console that without the logger.

Filter on a Specific Class

We can filter items when we’re logging so that we don’t see so many items.

For example, we can write:

const { MongoClient, Logger } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    Logger.setLevel("debug");
    Logger.filter("class", ["Db"]);
    await client.connect();
    const db = client.db("test");
    db.dropCollection('test');
    db.createCollection('test');
    const testCollection = await db.collection('test');
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection.find();
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

The Logger.filter method with the ['Db'] array lets us display messages that are on the 'Db' class.

We can also customize the logger with our own class.

For example, we can write:

const { MongoClient, Logger } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

class CustomLogger {
  constructor() {
    this.logger = new Logger("A");
  }

log() {
    if (this.logger.isInfo()) {
      this.logger.info("logging A", {});
    }
  }
}

async function run() {
  try {
    const customLogger = new CustomLogger();
    customLogger.log();
    await client.connect();
    const db = client.db("test");
    db.dropCollection('test');
    db.createCollection('test');
    const testCollection = await db.collection('test');
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection.find();
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

We created the CustomLogger class and used its log method to do the logging.

Also, we can call setCurrentLogger to set a custom logger function:

const { MongoClient, Logger } = require('mongodb');
const connection = "mongodb://localhost:27017";
const client = new MongoClient(connection);

async function run() {
  try {
    Logger.setLevel("debug");
    Logger.setCurrentLogger((msg, context) => {
      context['foo'] = 'bar';
      msg = `Hello, World. ${msg}`;
      console.log(msg, context);
    });
    await client.connect();
    const db = client.db("test");
    db.dropCollection('test');
    db.createCollection('test');
    const testCollection = await db.collection('test');
    const result = await testCollection.insertMany([
      { "_id": 1, "name": "apples", "qty": 5, "rating": 3 },
      { "_id": 2, "name": "apples", "qty": 7, "rating": 1 },
      { "_id": 3, "name": "oranges", "qty": 6, "rating": 2 },
      { "_id": 4, "name": "avocados", "qty": 3, "rating": 5 },
    ]);
    console.log(result)
    const cursor = await testCollection.find();
    cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

The msg parameter has the message. The context has additional data about the event that’s logged.

Conclusion

We can add a logger to our MongoDB code with the Node.js MongoDB client.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *