You can write custom log entries from your MongoDB Shell scripts. 您可以从MongoDB Shell脚本中编写自定义日志条目。Custom log entries help with debugging, error handling, and alert you when the script performs specific functions.自定义日志条目有助于调试、错误处理,并在脚本执行特定功能时提醒您。
About this Task关于此任务
MongoDB Shell supports the following methods for custom log entries:MongoDB Shell支持以下自定义日志条目的方法:
log.debug()log.error()log.fatal()log.info()log.warn()
Steps步骤
Create a script that writes a custom log entry创建一个编写自定义日志条目的脚本
The following script inserts documents into the 以下脚本将文档插入到movies collection and writes a custom info log entry. If the script errors, it writes a custom error log entry instead.movies集合中,并写入自定义info日志条目。如果脚本出错,它会写入自定义error日志条目。
// connect-and-insert-with-log-entry.js
try {
db = connect( 'mongodb://localhost/myDatabase' );
db.movies.insertMany( [
{
title: 'Titanic',
year: 1997,
genres: [ 'Drama', 'Romance' ]
},
{
title: 'Spirited Away',
year: 2001,
genres: [ 'Animation', 'Adventure', 'Family' ]
},
{
title: 'Casablanca',
genres: [ 'Drama', 'Romance', 'War' ]
}
] )
log.info('InsertData: Inserted 3 movies');
} catch (error) {
log.error('Insert failed', { error: error.message });
}
Save the script as 将脚本保存为connect-and-insert-with-log-entry.js.connect-and-insert-with-log-entry.js。
Run the script运行脚本
To run the 要运行connect-and-insert-with-log-entry.js script, use mongosh to connect to your deployment and run the following command within MongoDB Shell:connect-and-insert-with-log-entry.js脚本,请使用mongosh连接到部署,并在MongoDB Shell中运行以下命令:
load("connect-and-insert-with-log-entry.js")
Alternatively, you can run the script programmatically by using the 或者,您可以在启动--file option when you start mongosh:mongosh时使用--file选项以编程方式运行脚本:
mongosh --file connect-and-insert-with-log-entry.jsResults结果
The custom log entry appears in the logs for your session:自定义日志条目将出现在会话的日志中:
{"t":{"$date":"2025-02-25T18:04:01.690Z"},"s":"I","c":"MONGOSH-SCRIPTS","id":1000000054,"ctx":"custom-log","msg":"InsertData: Inserted 3 movies"}
For more information about log sessions and how to retrieve log messages, see View Shell Logs.有关日志会话以及如何检索日志消息的更多信息,请参阅查看Shell日志。
To verify that the script inserted the documents, query the 要验证脚本是否插入了文档,请查询movies collection:movies集:
use myDatabase
db.movies.find()
Output:输出:
[
{
_id: ObjectId('67bde8c2a527c6b1341979f2'),
title: 'Titanic',
year: 1997,
genres: [ 'Drama', 'Romance' ]
},
{
_id: ObjectId('67bde8c2a527c6b1341979f3'),
title: 'Spirited Away',
year: 2001,
genres: [ 'Animation', 'Adventure', 'Family' ]
},
{
_id: ObjectId('67bde8c2a527c6b1341979f4'),
title: 'Casablanca',
genres: [ 'Drama', 'Romance', 'War' ]
}
]