Docs Menu
Docs Home
/ / /
Node.js ドライバー
/

アプリケーション イベントの監視

このガイドでは、 MongoDB Node.jsドライバーで監視を設定および構成する方法を学習できます。

モニタリングには、実行中のプログラムのアクティビティに関する情報を収集することが含まれます。この情報はアプリケーションパフォーマンス マネジメント ライブラリで使用できます。

Node.jsドライバーをモニタリングすると、ドライバーのリソース使用量とパフォーマンスを理解でき、アプリケーション の設計とデバッグ時に情報に基づいた決定を行うことができます。

このガイドでは、次のタスクを実行する方法を説明します。

  • コマンド イベントの監視

  • サーバー検出とモニタリング(SDAM)イベントの監視

  • 接続プール イベントの監視

このガイドでは、コード内でドライバーのアクティビティに関する情報を使用する方法を説明します。ドライバーでイベントをレコード方法については、 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

コマンドが開始されたときに作成されます。

commandSucceeded

コマンドが成功したときに作成されます。

commandFailed

コマンドが失敗した場合に作成されます。

CommandStartedEvent {
requestId: 1534,
databaseName: "app",
commandName: "find",
address: 'localhost:27017',
connectionId: 812613,
command: {
find: { firstName: "Jane", lastName: "Doe" }
}
}
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
}
}
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 イベントのいずれかにサブスクライブできます。

イベント名
説明

serverOpening

インスタンスへの接続が開いたときに作成されます。

serverClosed

インスタンスへの接続が閉じられたときに作成されます。

serverDescriptionChanged

インスタンスの状態が変更されたときに作成されます(セカンダリからプライマリへなど)。

topologyOpening

インスタンスへの接続を試みる前に作成されます。

topologyClosed

トポロジー内のすべてのインスタンス接続が閉じた後に作成されます。

topologyDescriptionChanged

新しいプライマリの選挙やmongosプロキシの切断など、トポロジーが変更されたときに作成されます。

serverHeartbeatStarted

MongoDB インスタンスにhelloコマンドを発行する前に作成されます。

serverHeartbeatSucceeded

helloコマンドが MongoDB インスタンスから正常に返されたときに作成されます。

serverHeartbeatFailed

特定の MongoDB インスタンスに対して発行されたhelloコマンドが成功した応答を返すのに失敗した場合に作成されます。

次のセクションは、各 SDAM イベントのタイプごとのサンプル出力を示しています。

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フィールドには、次のいずれかの可能な値が含まれています。

タイプ
説明

Unknown

不明なインスタンス

Standalone

スタンドアロン インスタンス

Mongos

Mongos プロキシ インスタンス

PossiblePrimary

少なくとも 1 つのサーバーがこれをプライマリとして認識しますが、すべての インスタンスによってまだ検証されていません。

RSPrimary

プライマリ インスタンス

RSSecondary

セカンダリ インスタンス

RSArbiter

アービタ インスタンス

RSOther

RSGhost

RSGhost および RSその他の仕様 を参照してください。 詳細については、

ServerHeartbeatStartedEvent {
connectionId: 'localhost:27017'
}
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'
}
ServerHeartbeatFailed {
duration: 20,
failure: MongoError('some error'),
connectionId: 'localhost:27017'
}
ServerOpeningEvent {
topologyId: 0,
address: 'localhost:27017'
}
ServerClosedEvent {
topologyId: 0,
address: 'localhost:27017'
}
TopologyOpeningEvent {
topologyId: 0
}
TopologyClosedEvent {
topologyId: 0
}
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フィールドには、次のいずれかの可能な値が含まれています。

タイプ
説明

Single

スタンドアロン インスタンス

ReplicaSetWithPrimary

プライマリがあるレプリカセット

ReplicaSetNoPrimary

プライマリのないレプリカセット

Sharded

シャーディングされたクラスター

Unknown

不明なトポロジー

接続プールとは、ドライバーが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
};
}

次の接続プール モニタリング イベントのいずれかにサブスクライブできます。

イベント名
説明

connectionPoolCreated

接続プールが作成されたときに作成されます。

connectionPoolReady

接続プールが準備できたときに作成されます。

connectionPoolClosed

サーバー インスタンスが破棄される前に接続プールが閉じられたときに作成されます。

connectionCreated

接続が作成されたときに作成されますが、操作に使用される場合は必ずしも作成されません。

connectionReady

接続がハンドシェイクを正常に完了し、操作に使用する準備が整った後に作成されます。

connectionClosed

接続が閉じられたときに作成されます。

connectionCheckOutStarted

操作が実行用接続を取得しようとしたときに作成されます。

connectionCheckOutFailed

操作が実行用接続の取得に失敗した場合に作成されます。

connectionCheckedOut

操作が実行用接続を正常に取得したときに作成されます。

connectionCheckedIn

操作が実行された後に接続がプールにチェックバックされたときに作成されます。

connectionPoolCleared

すべての接続が閉じられ、接続プールがクリアされたときに作成されます。

次のセクションでは、接続プールを監視するイベントの各タイプのサンプル出力を示します。

ConnectionPoolCreatedEvent {
time: 2023-02-13T15:54:06.944Z,
address: '...',
options: {...}
}
ConnectionPoolReadyEvent {
time: 2023-02-13T15:56:38.440Z,
address: '...'
}
ConnectionPoolClosedEvent {
time: 2023-02-13T15:56:38.440Z,
address: '...'
}
ConnectionCreatedEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
connectionId: 1
}
ConnectionReadyEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
connectionId: 1,
durationMS: 60
}
ConnectionClosedEvent {
time: 2023-02-13T15:56:38.439Z,
address: '...',
connectionId: 1,
reason: 'poolClosed',
serviceId: undefined
}
ConnectionCheckOutStartedEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
}
ConnectionCheckOutFailedEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
reason: ...,
durationMS: 60
}
ConnectionCheckedOutEvent {
time: 2023-02-13T15:54:07.188Z,
address: '...',
connectionId: 1,
durationMS: 60
}
ConnectionCheckedInEvent {
time: 2023-02-13T15:54:07.189Z,
address: '...',
connectionId: 1
}
ConnectionPoolClearedEvent {
time: 2023-02-13T15:56:38.439Z,
address: '...',
serviceId: undefined,
interruptInUseConnections: true,
}

このガイドで説明したオプションやタイプの詳細については、次のAPIドキュメントを参照してください。

戻る

モニタリングとロギング

項目一覧

  • Overview
  • イベントの監視
  • コマンド イベント
  • イベントの説明
  • サーバー検出と監視イベント
  • イベント サブスクリプションの例
  • イベントの説明
  • イベント ドキュメントの例
  • 接続プール イベント
  • イベント サブスクリプションの例
  • イベントの説明
  • イベント ドキュメントの例
  • API ドキュメント