MongoDB Shell スクリプト からカスタム ログエントリを書込み (write) できます。カスタムログエントリは、デバッグ、エラー処理、およびスクリプトが特定の機能を実行したときにアラートするのに役立ちます。
このタスクについて
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' ] } ]