Docs Home / Node.js Driver

Logging日志记录

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:在本指南中,您可以学习如何在Node.js驱动程序中配置记录器。驱动程序允许您记录按以下严重级别分类的信息:

  • 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.上述列表按严重性级别降序排列。指定严重性级别还会记录所有严重性级别较高的消息。例如,将日志级别设置为critical(严重)也会导致日志消息具有emergency(紧急)和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.您可以通过指定环境变量在Node.js驱动程序中配置日志记录,而无需更改代码。您还可以通过在MongoClient构造函数中指定客户端选项来以编程方式配置日志记录。

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 components:指定任何未设置组件的默认严重性
  • MONGODB_LOG_COMMAND: Logs all commands sent to the server:记录发送到服务器的所有命令
  • MONGODB_LOG_TOPOLOGY: Logs any changes to the cluster topology:记录群集拓扑的任何更改
  • MONGODB_LOG_SERVER_SELECTION: Logs the server selection process:记录服务器选择过程
  • MONGODB_LOG_CONNECTION: Logs all connection pool events:记录所有连接池事件
  • MONGODB_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.如果不指定上述任何环境变量,驱动程序将使用MONGODB_LOG_ALL的值,如果不指定,则隐式设置为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:以下示例为除MONGODB_LOG_COMMAND之外的所有要debug(调试)的组件设置日志级别:

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:您可以通过将MONGODB_LOG_PATH环境变量设置为"stderr""stdout"来指定驱动程序是登录到stderr还是stdout,如下例所示:

export MONGODB_LOG_PATH="stderr"

By default, the driver logs to stderr.默认情况下,驱动程序会登录到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.驱动程序使用EJSON对记录的文档进行字符串化,默认情况下字符串限制为1000个字符。您可以通过指定MONGODB_LOG_MAX_DOCUMENT环境变量来指定记录器的最大文档长度。将此变量设置为0以不执行截断。

The following example sets the maximum document length to 500 characters:以下示例将最大文档长度设置为500个字符:

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.您可以通过在MongoClient构造函数中指定客户端选项来以编程方式配置日志记录。因为客户端选项优先于环境变量,所以只有当您不再希望驱动程序响应环境变量时,才在客户端中指定它们。

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.如果您的应用程序依赖stdoutstderr格式,我们建议使用客户端选项配置日志记录,以避免与应用程序用户的环境变量冲突。

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 components:指定任何未设置组件的默认严重性
  • command: Logs all commands sent to the server:记录发送到服务器的所有命令
  • topology: Logs any changes to the cluster topology:记录群集拓扑的任何更改
  • serverSelection: Logs the server selection process:记录服务器选择过程
  • connection: Logs all connection pool events:记录所有连接池事件
  • client: 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:要为组件指定日志级别,请将mongodbLogComponentSeverities选项设置为包含该组件和所需严重性级别的对象。以下示例为除command之外的所有要debug的组件设置日志级别:

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:您可以通过将mongodbLogPath选项设置为"stderr""stdout"来指定驱动程序是登录到stderr还是stdout,如下例所示:

const mongodbLogComponentSeverities = {
default: "debug"
};

const mongodbLogPath = "stdout";
const client = new MongoClient("<connection string>",
{ mongodbLogComponentSeverities, mongodbLogPath }
);

By default, the driver logs to stderr.默认情况下,驱动程序会登录到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.如果你的函数在写操作中抛出错误,抛出的错误将结束记录器。因此,我们建议您通过将write函数设置为no操作来处理错误,而不是抛出错误,如上例所示。

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.驱动程序使用EJSON对记录的文档进行字符串化,默认情况下字符串限制为1000个字符。您可以通过指定mongodbLogMaxDocumentLength选项来指定记录器的最大文档长度。将此选项设置为0以不执行截断。

The following example sets the maximum document length to 500 characters:以下示例将最大文档长度设置为500个字符:

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 Monitoring guide.有关使用Node.js驱动程序进行监控的更多信息,请参阅监控指南

API Documentation文档

To learn more about any of the options or types discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何选项或类型的更多信息,请参阅以下API文档: