Logging
On this page
Overview
In this guide, you can learn how to configure a logger in the Node.js driver. The driver allows you to log information categorized at following severity levels:
emergency
alert
critical
error
warn
notice
info
debug
trace
off
The preceding list is ordered by decreasing severity level. Specifying a severity
level also logs all messages with higher severity levels. For example, setting
the log level to critical
also results in log messages with severity levels of
emergency
and alert
.
The lower the severity level you specify, the more information the driver logs, which might impact the performance of your application.
Configuration
You can configure logging in the Node.js driver without code changes by
specifying environment variables. You can also configure logging
programmatically by specifying client options in the MongoClient
constructor.
Note
Because connection strings are often shared among a deployment of different appications that might have different logging support, we do not recommend using a connection string to configure logging.
Environment Variables
You can configure logging for different components of the driver by specifying a severity level in one or more of the following environment variables:
MONGODB_LOG_ALL
: Specifies the default severity for any unset componentsMONGODB_LOG_COMMAND
: Logs all commands sent to the serverMONGODB_LOG_TOPOLOGY
: Logs any changes to the cluster topologyMONGODB_LOG_SERVER_SELECTION
: Logs the server selection processMONGODB_LOG_CONNECTION
: Logs all connection pool eventsMONGODB_LOG_CLIENT
: Logs all client events
If you don't specify any of the preceding environment variables, the driver uses
the value of MONGODB_LOG_ALL
, which if not specified, is implicitly set to
off
.
Tip
Logging at the command level is the most performance-heavy logging option due to the frequency in which commands are sent to the server. Only specify this option if necessary for debugging your application.
The following example sets the log level for all components to debug
except
for MONGODB_LOG_COMMAND
:
export MONGODB_LOG_ALL="debug" export MONGODB_LOG_COMMAND="off"
Log Location
You can specify whether the driver logs to stderr
or stdout
by setting
the MONGODB_LOG_PATH
environment variable to "stderr"
or "stdout"
,
as shown in the following example:
export MONGODB_LOG_PATH="stderr"
By default, the driver logs to stderr
.
Document Length
The driver stringifies logged documents by using EJSON, which limits strings to
1000 characters by default. You can specify a maximum document length for your
logger by specifying the MONGODB_LOG_MAX_DOCUMENT
environment variable. Set
this variable to 0
to not perform truncation.
The following example sets the maximum document length to 500 characters:
export MONGODB_LOG_MAX_DOCUMENT_LENGTH=500
Client Options
You can configure logging programmatically by specifying client options in the
MongoClient
constructor. Because client options take precedence over environment
variables, only specify them in the client if you no longer want the driver to
respond to environment variables.
Tip
If your application relies on the format of stdout
or stderr
, we
recommend configuring logging by using client options to avoid conflicts with
your application user's environment variables.
You can specify which component to configure logging for by specifying one or more of the following client options:
default
: Specifies the default severity for any unset componentscommand
: Logs all commands sent to the servertopology
: Logs any changes to the cluster topologyserverSelection
: Logs the server selection processconnection
: Logs all connection pool eventsclient
: Logs all client events
To specify a log level for a component, set the
mongodbLogComponentSeverities
option to an object that contains the
component and your desired severity level. The following example sets the log
level for all components to debug
except for command
:
const client = new MongoClient("<connection string>", { mongodbLogComponentSeverities: { default: "debug", command: "off" } });
Log Location
You can specify whether the driver logs to stderr
or stdout
by setting
the mongodbLogPath
option to "stderr"
or "stdout"
, as shown in the
following example:
const mongodbLogComponentSeverities = { default: "debug" }; const mongodbLogPath = "stdout"; const client = new MongoClient("<connection string>", { mongodbLogComponentSeverities, mongodbLogPath } );
By default, the driver logs to stderr
.
You can also specify a custom log destination. The following example creates a custom log destination:
import fs from 'node:fs/promises'; import util from 'node:util'; const mongodbLogPath = { file: await fs.open(`./server-${+new Date()}.logs`, 'w'), async write(log) { try { await this.file?.appendFile(util.inspect(log) + '\n'); } catch (fileError) { console.log('cannot log anymore', fileError); this.file = null; } } } const client = new MongoClient("<connection string>", { mongodbLogPath });
If your function throws an error in the write operation, the thrown error ends the logger. Because of this, we recommend that you handle errors by making the write function a no-op rather than throwing an error, as shown in the preceding example.
Note
Logging can exhaust disk space if the proper log rotation system is not in place. We recommend that you connect your custom write function to a popular logging library.
Document Length
The driver stringifies logged documents by using EJSON, which limits strings to
1000 characters by default. You can specify a maximum document length for your
logger by specifying the mongodbLogMaxDocumentLength
option. Set
this option to 0
to perform no truncation.
The following example sets the maximum document length to 500 characters:
const mongodbLogComponentSeverities = { default: "debug" }; const mongodbLogLength = 500; const client = new MongoClient("<connection string>", { mongodbLogComponentSeverities, mongodbLogLength });
Additional Information
For more information about monitoring with the Node.js driver, see the following monitoring guides:
API Documentation
To learn more about any of the options or types discussed in this guide, see the following API documentaion: