アプリケーション イベントの監視
Overview
このガイドでは、 MongoDB Node.jsドライバーで監視を設定および構成する方法を学習できます。
モニタリングには、実行中のプログラムのアクティビティに関する情報を収集することが含まれます。この情報はアプリケーションパフォーマンス マネジメント ライブラリで使用できます。
Node.jsドライバーをモニタリングすると、ドライバーのリソース使用量とパフォーマンスを理解でき、アプリケーション の設計とデバッグ時に情報に基づいた決定を行うことができます。
このガイドでは、次のタスクを実行する方法を説明します。
このガイドでは、コード内でドライバーのアクティビティに関する情報を使用する方法を説明します。ドライバーでイベントをレコード方法については、 Node.jsドライバーの ログ記録ガイド を参照してください。
イベントの監視
Node.jsドライバーを使用してイベントを監視するには、アプリケーションでノードをサブスクライブしてください。
イベントは、操作中にドライバー内で発生する任意のアクションです。 Node.jsドライバーには、これらのイベントのサブセットをリッスンする機能が含まれています。
Node.jsドライバーは、定義するイベントを次のカテゴリに整理します。
コマンド イベント
サーバー検出とモニタリング(SDAM)イベント
接続プール イベント
次のセクションでは、各イベント カテゴリをモニターする方法を示します。
コマンド イベント
コマンドイベントは、 MongoDBデータベースコマンドに関連するイベントです。アプリケーションでサブスクライブすることで、ドライバーを使用して 1 つ以上のコマンド モニタリング イベントにアクセスできます。
MongoDBデータベースコマンドの詳細については、サーバー マニュアルの「 データベースコマンド 」ガイドを参照してください。
注意
コマンド モニタリングはデフォルトで無効になっています。 コマンドモニタリングを有効にするには、 monitorCommands
オプションをtrue
としてMongoClient
コンストラクターに渡します。
例
次の例は、レプリカセットへの接続と、 MongoDBデプロイによって作成されたコマンド監視イベントの 1 つへのサブスクライブを示しています。
/* Subscribe to an event */ const { MongoClient } = require("mongodb"); // Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri, { monitorCommands:true }); // Replace <event name> with the name of the event you are subscribing to const eventName = "<event name>"; // Subscribes to a specified event and print a message when the event is received client.on(eventName, event => console.log(event)); async function run() { try { // Establishes and verifies connection to the "admin" database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // Closes the database connection on completion or error await client.close(); } } run().catch(console.dir);
イベントの説明
次のコマンド モニタリング イベントのいずれかにサブスクライブできます。
イベント名 | 説明 |
---|---|
| コマンドが開始されたときに作成されます。 |
| コマンドが成功したときに作成されます。 |
| コマンドが失敗した場合に作成されます。 |
commandStarted
CommandStartedEvent { requestId: 1534, databaseName: "app", commandName: "find", address: 'localhost:27017', connectionId: 812613, command: { find: { firstName: "Jane", lastName: "Doe" } } }
commandSucceeded
CommandSucceededEvent { requestId: 1534, commandName: "find", address: 'localhost:27017', connectionId: 812613, duration: 15, reply: { cursor: { firstBatch: [ { _id: ObjectId("5e8e2ca217b5324fa9847435"), firstName: "Jane", lastName: "Doe" } ], _id: 0, ns: "app.users" }, ok: 1, operationTime: 1586380205 } }
commandFailed
CommandFailedEvent { requestId: 1534, commandName: "find", address: 'localhost:27017', connectionId: 812613, failure: Error("something failed"), duration: 11 }
サーバー検出と監視イベント
Node.jsドライバーは、接続したインスタンスまたはクラスターの状態が変化した場合に、SDAM イベントとも呼ばれるトポロジーイベントを作成します。例、新しい接続を確立するか、クラスターが新しい プライマリノードを選択した場合、ドライバーはイベントを作成します。
トポロジーイベントの詳細については、サーバー マニュアルの レプリケーションガイドを参照してください。
次のセクションでは、アプリケーション内のトポロジーの変更を記録し、これらのイベントで提供される情報を調べる方法を示します。
イベント サブスクリプションの例
アプリケーションでサブスクライブすることで、1 つ以上の SDAM イベントにアクセスできます。次の例では、レプリカセットに接続し、 MongoDBデプロイによって作成された SDAM イベントの 1 つにサブスクライブする方法を示します。
/* Subscribe to SDAM event */ const { MongoClient } = require("mongodb"); // Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri); // Replace <event name> with the name of the event you are subscribing to const eventName = "<event name>"; // Subscribes to a specified event and prints a message when the event is received client.on(eventName, event => { console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`); }); async function run() { try { // Establishes and verifies connection to the database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // Closes the database connection on completion or error await client.close(); } } run().catch(console.dir);
イベントの説明
次の SDAM イベントのいずれかにサブスクライブできます。
イベント名 | 説明 |
---|---|
| インスタンスへの接続が開いたときに作成されます。 |
| インスタンスへの接続が閉じられたときに作成されます。 |
| インスタンスの状態が変更されたときに作成されます(セカンダリからプライマリへなど)。 |
| インスタンスへの接続を試みる前に作成されます。 |
| トポロジー内のすべてのインスタンス接続が閉じた後に作成されます。 |
| 新しいプライマリの選挙やmongosプロキシの切断など、トポロジーが変更されたときに作成されます。 |
| MongoDB インスタンスに |
|
|
| 特定の MongoDB インスタンスに対して発行された |
イベント ドキュメントの例
次のセクションは、各 SDAM イベントのタイプごとのサンプル出力を示しています。
server Description Changed
ServerDescriptionChangedEvent { topologyId: 0, address: 'localhost:27017', previousDescription: ServerDescription { address: 'localhost:27017', error: null, roundTripTime: 0, lastUpdateTime: 1571251089030, lastWriteDate: null, opTime: null, type: 'Unknown', minWireVersion: 0, maxWireVersion: 0, hosts: [], passives: [], arbiters: [], tags: [] }, newDescription: ServerDescription { address: 'localhost:27017', error: null, roundTripTime: 0, lastUpdateTime: 1571251089051, lastWriteDate: 2019-10-16T18:38:07.000Z, opTime: { ts: Timestamp, t: 18 }, type: 'RSPrimary', minWireVersion: 0, maxWireVersion: 7, maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, maxWriteBatchSize: 100000, me: 'localhost:27017', hosts: [ 'localhost:27017' ], passives: [], arbiters: [], tags: [], setName: 'rs', setVersion: 1, electionId: ObjectID, primary: 'localhost:27017', logicalSessionTimeoutMinutes: 30, '$clusterTime': ClusterTime } }
このイベントのServerDescription
オブジェクトのtype
フィールドには、次のいずれかの可能な値が含まれています。
タイプ | 説明 |
---|---|
| 不明なインスタンス |
| スタンドアロン インスタンス |
| Mongos プロキシ インスタンス |
| 少なくとも 1 つのサーバーがこれをプライマリとして認識しますが、すべての インスタンスによってまだ検証されていません。 |
| プライマリ インスタンス |
| セカンダリ インスタンス |
| アービタ インスタンス |
| 詳細については、 RSGhost および RS Other 仕様 を参照してください |
| RSGhost および RSその他の仕様 を参照してください。 詳細については、 |
server heartbeatStarted
ServerHeartbeatStartedEvent { connectionId: 'localhost:27017' }
serverハートビートSucceeded
ServerHeartbeatSucceededEvent { duration: 1.939997, reply:{ hosts: [ 'localhost:27017' ], setName: 'rs', setVersion: 1, isWritablePrimary: true, secondary: false, primary: 'localhost:27017', me: 'localhost:27017', electionId: ObjectID, lastWrite: { opTime: { ts: [Timestamp], t: 18 }, lastWriteDate: 2019-10-16T18:38:17.000Z, majorityOpTime: { ts: [Timestamp], t: 18 }, majorityWriteDate: 2019-10-16T18:38:17.000Z }, maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, maxWriteBatchSize: 100000, localTime: 2019-10-16T18:38:19.589Z, logicalSessionTimeoutMinutes: 30, minWireVersion: 0, maxWireVersion: 7, readOnly: false, ok: 1, operationTime: Timestamp, '$clusterTime': ClusterTime }, connectionId: 'localhost:27017' }
server heartbeatFailed
ServerHeartbeatFailed { duration: 20, failure: MongoError('some error'), connectionId: 'localhost:27017' }
server全体の開始
ServerOpeningEvent { topologyId: 0, address: 'localhost:27017' }
serverClosed
ServerClosedEvent { topologyId: 0, address: 'localhost:27017' }
topic
TopologyOpeningEvent { topologyId: 0 }
トポロジーが閉じた
TopologyClosedEvent { topologyId: 0 }
topic
TopologyDescriptionChangedEvent { topologyId: 0, previousDescription: TopologyDescription { type: 'ReplicaSetNoPrimary', setName: null, maxSetVersion: null, maxElectionId: null, servers: Map { 'localhost:27017' => ServerDescription }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: null, heartbeatFrequencyMS: 10000, localThresholdMS: 15, options: Object, error: undefined, commonWireVersion: null }, newDescription: TopologyDescription { type: 'ReplicaSetWithPrimary', setName: 'rs', maxSetVersion: 1, maxElectionId: null, servers: Map { 'localhost:27017' => ServerDescription }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: 30, heartbeatFrequencyMS: 10000, localThresholdMS: 15, options: Object, error: undefined, commonWireVersion: 7 } }
このイベントのTopologyDescription
オブジェクトのtype
フィールドには、次のいずれかの可能な値が含まれています。
タイプ | 説明 |
---|---|
| スタンドアロン インスタンス |
| プライマリがあるレプリカセット |
| プライマリのないレプリカセット |
| シャーディングされたクラスター |
| 不明なトポロジー |
接続プール イベント
接続プールとは、ドライバーがMongoDBインスタンスと維持するオープン TCP 接続のセットです。接続プールは、アプリケーションが実行する必要があるネットワーク ハンドシェイクの数を減らし、アプリケーションの実行を高速化するのに役立ちます。
次のセクションでは、アプリケーションで接続プール イベントを記録し、これらのイベントで提供される情報を調べる方法を示します。
イベント サブスクリプションの例
アプリケーションでサブスクライブすることで、ドライバーを使用して 1 つ以上の接続プール イベントにアクセスできます。 次の例は、レプリカセットへの接続と、MongoDB 配置によって作成された接続プール監視イベントの 1 つへのサブスクライブを示しています。
const { MongoClient } = require("mongodb"); // Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri); // Replace <event name> with the name of the event you are subscribing to const eventName = "<event name>"; // Subscribes to the event client.on(eventName, (event) => console.log("\nreceived event:\n", event) ); async function run() { try { // Establishes and verifies connection await client.db("admin").command({ ping: 1 }); console.log("\nConnected successfully!\n"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
接続プール モニタリング イベントは、アプリケーションの接続プールの動作をデバッグして理解するのに役立ちます。 次の例では、接続プール モニタリング イベントを使用して、プール内のチェックアウトされた接続の数を返します。
function connectionPoolStatus(client) { let checkedOut = 0; function onCheckout() { checkedOut++; } function onCheckin() { checkedOut--; } function onClose() { client.removeListener('connectionCheckedOut', onCheckout); client.removeListener('connectionCheckedIn', onCheckin); checkedOut = NaN; } // Decreases count of connections checked out of the pool when connectionCheckedIn event is triggered client.on('connectionCheckedIn', onCheckin); // Increases count of connections checked out of the pool when connectionCheckedOut event is triggered client.on('connectionCheckedOut', onCheckout); // Cleans up event listeners when client is closed client.on('close', onClose); return { count: () => checkedOut, cleanUp: onClose }; }
イベントの説明
次の接続プール モニタリング イベントのいずれかにサブスクライブできます。
イベント名 | 説明 |
---|---|
| 接続プールが作成されたときに作成されます。 |
| 接続プールが準備できたときに作成されます。 |
| サーバー インスタンスが破棄される前に接続プールが閉じられたときに作成されます。 |
| 接続が作成されたときに作成されますが、操作に使用される場合は必ずしも作成されません。 |
| 接続がハンドシェイクを正常に完了し、操作に使用する準備が整った後に作成されます。 |
| 接続が閉じられたときに作成されます。 |
| 操作が実行用接続を取得しようとしたときに作成されます。 |
| 操作が実行用接続の取得に失敗した場合に作成されます。 |
| 操作が実行用接続を正常に取得したときに作成されます。 |
| 操作が実行された後に接続がプールにチェックバックされたときに作成されます。 |
| すべての接続が閉じられ、接続プールがクリアされたときに作成されます。 |
イベント ドキュメントの例
次のセクションでは、接続プールを監視するイベントの各タイプのサンプル出力を示します。
connectionPoolCreed
ConnectionPoolCreatedEvent { time: 2023-02-13T15:54:06.944Z, address: '...', options: {...} }
connectionPoolReady
ConnectionPoolReadyEvent { time: 2023-02-13T15:56:38.440Z, address: '...' }
connectionPoolClosed
ConnectionPoolClosedEvent { time: 2023-02-13T15:56:38.440Z, address: '...' }
connectionCreed
ConnectionCreatedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', connectionId: 1 }
connectionReady
ConnectionReadyEvent { time: 2023-02-13T15:56:38.291Z, address: '...', connectionId: 1, durationMS: 60 }
connectionClosed
ConnectionClosedEvent { time: 2023-02-13T15:56:38.439Z, address: '...', connectionId: 1, reason: 'poolClosed', serviceId: undefined }
connectionCheckOutStarted
ConnectionCheckOutStartedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', }
connectionCheckOutFailed
ConnectionCheckOutFailedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', reason: ..., durationMS: 60 }
connectionCheckedOut
ConnectionCheckedOutEvent { time: 2023-02-13T15:54:07.188Z, address: '...', connectionId: 1, durationMS: 60 }
connectionCheckedIn
ConnectionCheckedInEvent { time: 2023-02-13T15:54:07.189Z, address: '...', connectionId: 1 }
connectionPoolCleared
ConnectionPoolClearedEvent { time: 2023-02-13T15:56:38.439Z, address: '...', serviceId: undefined, interruptInUseConnections: true, }
API ドキュメント
このガイドで説明したオプションやタイプの詳細については、次のAPIドキュメントを参照してください。