======= Logging ======= You can change the log level, filter on classes to allow only specific classes to log, and provide your own logger implementation. Setting Log level ----------------- The driver allows logging at three different levels: ``debug``, ``info`` and ``error``. The default level is ``error``. The following example demonstrates how to set the logger to ``debug``. .. code-block:: js const { MongoClient, Logger } = require('mongodb'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; const client = new MongoClient(url); async function main(client) { // Set debug level Logger.setLevel('debug'); const db = client.db('myproject'); // Execute command { isMaster: true } against db await db.command({ isMaster: true }); } // Function to connect to the server and run your code async function run() { try { // Connect the client to the server await client.connect(); console.log('Connected successfully to server'); await main(client); } finally { // Ensures that the client will close when you finish/error await client.close(); } } // Runs your code run(); Filtering On specific classes ----------------------------- You can set the Logger to only log specific class names. The following example demonstrates how to log only the ``Db`` class. .. code-block:: js async function main(client) { // Set debug level Logger.setLevel('debug'); // Only log statements on 'Db' class Logger.filter('class', ['Db']); const db = client.db('myproject'); // Execute command { isMaster: true } against db await db.command({ isMaster: true }); } Driver classes available for filtering: * ``Db``\ : The Db instance log statements * ``Server``\ : A server instance (either standalone, a mongos or replica set member) * ``ReplSet``\ : Replica set related log statements * ``Mongos``\ : Mongos related log statements * ``Cursor``\ : Cursor log statements * ``Pool``\ : Connection Pool specific log statements * ``Connection``\ : Singular connection specific log statements * ``Ping``\ : Replica set ping inquiry log statements You can add your own classes to the logger by creating your own logger instances. .. code-block:: js const { Logger } = require('mongodb'); class A { constructor() { this.logger = new Logger('A'); } doSomething() { if (this.logger.isInfo()) { this.logger.info('logging A', {}); } } } // Execute A const a = new A(); a.doSomething(); Custom logger ------------- The following example demonstrates how to define a custom logger. .. code-block:: js async function main(client) { // Set debug level Logger.setLevel('debug'); // Set our own logger Logger.setCurrentLogger(function(msg, context) { console.log(msg, context); }); const db = client.db('myproject'); // Execute command { isMaster: true } against db await db.command({ isMaster: true }); }