Reputation: 1535
There's probably an obvious answer to this, but I can't seem to find it. I'm using Mongoose in my node app to connect to a MongoDB cluster. Is there any way to monitor the state of the client-side connection pool that Mongoose uses? Like a number of connection in the pool, number of connections currently checked-out from the pool, the rate at which connections are checked-out, etc? Bonus points if there's already a well established solution of exporting these metrics in Prometheus format.
Upvotes: 2
Views: 947
Reputation: 2618
If you are looking to get only stats for example via an API you can use this
mongoose.connection.db?.command({ serverStatus: 1})
.then(results => console.log("connections", results.connections))
.catch(error => console.error("command serverStatus error: ", error));
As results you will get something like this (same as what you get when running db.serverStatus().connections
in mongosh
):
connections {
current: 39,
available: 51161,
totalCreated: 740,
rejected: 0,
active: 21,
threaded: 39,
exhaustIsMaster: 0,
exhaustHello: 2,
awaitingTopologyChanges: 5
}
Upvotes: 0
Reputation: 2097
You can use the connection pool events. These events are triggered by specified pool-related events, such as connections, closures, and more.
Here’s a working example with the MongoDB module taken from the MongoDB official docs:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:31000,localhost:31001/?replicaSet=rs';
const client = new MongoClient(url);
client.on('connectionPoolCreated', event => console.dir(event));
client.on('connectionPoolClosed', event => console.dir(event));
client.on('connectionCreated', event => console.dir(event));
client.on('connectionReady', event => console.dir(event));
client.on('connectionClosed', event => console.dir(event));
client.on('connectionCheckOutStarted', event => console.dir(event));
client.on('connectionCheckOutFailed', event => console.dir(event));
client.on('connectionCheckedOut', event => console.dir(event));
client.on('connectionCheckedIn', event => console.dir(event));
client.on('connectionPoolCleared', event => console.dir(event));
client.connect((err, client) => {
if (err) throw err;
});
However, if you want to do this in Mongoose, you can use connection.getClient()
which returns the underlying mongodb client, bypassing the mongoose driver.
Method described in this GitHub issue
Upvotes: 3