您可以从 MongoDB Shell脚本 写入自定义 日志条目 。自定义日志条目有助于调试和错误处理,并在脚本执行特定功能时向您警报。
关于此任务
MongoDB Shell支持以下自定义日志条目的方法:
log.debug()
log.error()
log.fatal()
log.info()
log.warn()
步骤
1
创建写入自定义日志条目的脚本
以下脚本将文档插入 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 }); }
将脚本保存为 connect-and-insert-with-log-entry.js
。
2
运行脚本
要运行connect-and-insert-with-log-entry.js
脚本,请使用 mongosh
连接到您的部署并在MongoDB Shell中运行以下命令:
load("connect-and-insert-with-log-entry.js")
或者,您可以在启动 mongosh
时使用 --file
选项以编程方式运行脚本:
mongosh --file connect-and-insert-with-log-entry.js
结果
自定义日志条目将显示在会话日志中:
{"t":{"$date":"2025-02-25T18:04:01.690Z"},"s":"I","c":"MONGOSH-SCRIPTS","id":1000000054,"ctx":"custom-log","msg":"InsertData: Inserted 3 movies"}
有关日志会话以及如何检索日志消息的更多信息,请参阅查看Shell日志。
要验证脚本是否已插入文档,查询movies
集合:
use myDatabase db.movies.find()
输出:
[ { _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' ] } ]