Docs Menu
Docs Home
/
mongosh
/ /

カスタム ログ エントリの書込み

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' ]
}
]

戻る

ログのロケーションを指定する

項目一覧