Docs Menu
Docs Home
/ / /
Go Driver
/

Monitor Application Events

In this guide, you can learn how to set up and configure monitoring in the MongoDB Go Driver. You can monitor events by using the Go driver to subscribe to them in your application.

Monitoring involves collecting information about the activities of a running program, which you can use with an application performance management library.

An event is any action that occurs within the driver during its operation. The Go driver includes functionality for listening to a subset of these events.

Monitoring the Go driver lets you understand the driver's resource usage and performance, and can help you make informed decisions when designing and debugging your application.

In this guide you will learn how to perform these tasks:

  • Monitor Command Events

  • Monitor Server Discovery and Monitoring (SDAM) Events

  • Monitor Connection Pool Events

This guide shows how to use information about the activity of the driver in code. To learn how to record events in the driver, see the Go driver's Logging guide.

A command event is an event related to a MongoDB database command. You can access one or more command monitoring events by using the driver to subscribe to them in your application.

To learn more about MongoDB database commands, see the Database Commands guide in the Server Manual.

You can access details about command events by subscribing to them in your application. The following example demonstrates how to subscribe to the CommandStartedEvent event by instantiating a CommandMonitor and connecting to a deployment:

var eventArray []*event.CommandStartedEvent
cmdMonitor := &event.CommandMonitor{
Started: func(ctx context.Context, e *event.CommandStartedEvent) {
eventArray = append(eventArray, e)
},
}
clientOpts := options.Client().ApplyURI(uri).SetMonitor(cmdMonitor)
client, err := mongo.Connect(clientOpts)

You can subscribe to one or more of the following command monitoring events:

Event Name
Description

CommandStartedEvent

Created when a command starts.

CommandSucceededEvent

Created when a command succeeds.

CommandFailedEvent

Created when a command does not succeed.

The following sections show sample output for each type of command monitoring event.

*event.CommandStartedEvent
{
"Command": "...",
"DatabaseName": "...",
"CommandName": "...",
"RequestID": ...,
"ConnectionID": "...",
"ServerConnectionID": ...,
"ServiceID": "..."
}
*event.CommandSucceededEvent
{
"DurationNanos": 38717583,
"Duration": 38717583,
"CommandName": "insert",
"RequestID": 13,
"ConnectionID": "...",
"ServerConnectionID": ...,
"ServiceID": null,
"Reply": "..."
}
*event.CommandFailedEvent
{
"DurationNanos": 38717583,
"Duration": 38717583,
"CommandName": "insert",
"RequestID": 13,
"ConnectionID": "...",
"ServerConnectionID": ...,
"ServiceID": null,
"Failure": "..."
}

The Go driver creates topology events, also known as SDAM events, when there is a change in the state of the instance or cluster that you connected to. For example, the driver creates an event when you establish a new connection or if the cluster elects a new primary node.

The following sections demonstrate how to record topology changes in your application and explore the information provided in these events.

You can access details about SDAM events by subscribing to them in your application. The following example demonstrates how to subscribe to the ServerClosed event by instantiating a ServerMonitor and connecting to a deployment:

var eventArray []*event.ServerClosedEvent
srvMonitor := &event.ServerMonitor{
ServerClosed: func(e *event.ServerClosedEvent) {
eventArray = append(eventArray, e)
},
}
clientOpts := options.Client().ApplyURI(uri).SetServerMonitor(srvMonitor)
client, err := mongo.Connect(clientOpts)

You can subscribe to the following SDAM events by specifying properties of a ServerMonitor instance:

Event Name
Description

ServerDescriptionChangedEvent

Created when an instance state changes (such as from secondary to primary).

ServerOpeningEvent

Created when the server is initialized.

ServerClosedEvent

Created when the server is closed.

TopologyDescriptionChangedEvent

Created when the topology changes, such as an election of a new primary or disconnection of a mongos proxy.

TopologyOpeningEvent

Created when the topology is initialized.

TopologyClosedEvent

Created when the topology is closed.

ServerHeartbeatStartedEvent

Created when the heartbeat is started.

ServerHeartbeatSucceededEvent

Created when the heartbeat succeeds.

ServerHeartbeatFailedEvent

Created when the heartbeat fails.

The following sections show sample output for each type of SDAM event.

*event.ServerDescriptionChangedEvent
{
"Address": "...",
"TopologyID": "...",
"PreviousDescription": {
"Addr": "...",
"Arbiters": null,
"AverageRTT": 0,
"AverageRTTSet": false,
"Compression": null,
"CanonicalAddr": "...",
"ElectionID": "...",
"HeartbeatInterval": 0,
"HelloOK": false,
"Hosts": null,
"LastError": null,
"LastUpdateTime": "...",
"LastWriteTime": "...",
"MaxBatchCount": 0,
"MaxDocumentSize": 0,
"MaxMessageSize": 0,
"Members": null,
"Passives": null,
"Passive": false,
"Primary": "...",
"ReadOnly": false,
"ServiceID": null,
"SessionTimeoutMinutes": 0,
"SetName": "...",
"SetVersion": 0,
"Tags": null,
"TopologyVersion": null,
"Kind": 0,
"WireVersion": null
},
"NewDescription": {
"Addr": "...",
"Arbiters": null,
"AverageRTT": ...,
"AverageRTTSet": true,
"Compression": null,
"CanonicalAddr": "...",
"ElectionID": "...",
"HeartbeatInterval": ...,
"HelloOK": true,
"Hosts": [...],
"LastError": null,
"LastUpdateTime": "...",
"LastWriteTime": "...",
"MaxBatchCount": ...,
"MaxDocumentSize": ...,
"MaxMessageSize": ...,
"Members": [...],
"Passives": null,
"Passive": false,
"Primary": "...",
"ReadOnly": false,
"ServiceID": null,
"SessionTimeoutMinutes": 30,
"SetName": "...",
"SetVersion": 9,
"Tags": [...],
"TopologyVersion": {...},
"Kind": 10,
"WireVersion": {...}
}
}

The Kind field in an event document represents the type of a single server in a topology and can have the following values:

Value
Description

0

Unknown instance

1

Standalone instance

2

Replica set member

6

Primary instance

10

Secondary instance

18

Arbiter instance

34

Replica set ghost (a member that cannot be queried)

256

mongos proxy instance

512

Load balancer instance

*event.ServerOpeningEvent
{
"Address": "...",
"TopologyID": "..."
}
*event.ServerClosedEvent
{
"Address": "...",
"TopologyID": "..."
}

Important

Because the driver calls TopologyDescriptionChangedEvent when the deployment topology is locked, the callback (function argument) for this event must not attempt any operation that requires server selection on the same client.

*event.TopologyDescriptionChangedEvent
{
"TopologyID": "...",
"PreviousDescription": {
"Servers": [
{
"Addr": "...",
"Arbiters": null,
"AverageRTT": 0,
"AverageRTTSet": false,
"Compression": null,
"CanonicalAddr": "...",
"ElectionID": "...",
"HeartbeatInterval": 0,
"HelloOK": false,
"Hosts": null,
"LastError": null,
"LastUpdateTime": "...",
"LastWriteTime": "...",
"MaxBatchCount": 0,
"MaxDocumentSize": 0,
"MaxMessageSize": 0,
"Members": null,
"Passives": null,
"Passive": false,
"Primary": "...",
"ReadOnly": false,
"ServiceID": null,
"SessionTimeoutMinutes": 0,
"SetName": "...",
"SetVersion": 0,
"Tags": null,
"TopologyVersion": null,
"Kind": 0,
"WireVersion": null
},
...
],
"SetName": "...",
"Kind": 10,
"SessionTimeoutMinutes": 30,
"CompatibilityErr": null
},
"NewDescription": {
"Servers": [...],
"SetName": "...",
"Kind": 10,
"SessionTimeoutMinutes": 30,
"CompatibilityErr": null
}
}

To interpret the value of the Kind field, see the Kind Field Value section.

*event.TopologyOpeningEvent
{
"TopologyID": "..."
}
*event.TopologyClosedEvent
{
"TopologyID": "..."
}
*event.ServerHeartbeatStartedEvent
{
"ConnectionID": "...",
"Awaited": true
}
*event.ServerHeartbeatSucceededEvent
{
"DurationNanos": ...,
"Reply": {
"Addr": "...",
"Arbiters": null,
"AverageRTT": 0,
"AverageRTTSet": false,
"Compression": null,
"CanonicalAddr": "...",
"ElectionID": "...",
"HeartbeatInterval": 0,
"HelloOK": true,
"Hosts": [...],
"LastError": null,
"LastUpdateTime": "...",
"LastWriteTime": "...",
"MaxBatchCount": ...,
"MaxDocumentSize": ...,
"MaxMessageSize": ...,
"Members": [...],
"Passives": null,
"Passive": false,
"Primary": "...",
"ReadOnly": false,
"ServiceID": null,
"SessionTimeoutMinutes": 30,
"SetName": "...",
"SetVersion": 9,
"Tags": [...],
"TopologyVersion": {...},
"Kind": 6,
"WireVersion": {...}
},
"ConnectionID": "...",
"Awaited": true
}

To interpret the value of the Kind field, see the Kind Field Value section.

*event.ServerHeartbeatFailedEvent
{
"DurationNanos": ...,
"Failure": "<error message>"
"ConnectionID": "...",
"Awaited": true
}

A connection pool is a set of open TCP connections that your driver maintains with a MongoDB instance. Connection pools help reduce the number of network handshakes your application needs to perform and can help your application run faster.

The following sections demonstrate how to record connection pool events in your application and explore the information provided in these events.

You can access details about connection pool events by subscribing to them in your application. The following example demonstrates how to subscribe to the PoolEvent event by instantiating a PoolMonitor and connecting to a deployment:

var eventArray []*event.PoolEvent
cxnMonitor := &event.PoolMonitor{
Started: func(e *event.PoolEvent) {
eventArray = append(eventArray, e)
},
}
clientOpts := options.Client().ApplyURI(uri).SetPoolMonitor(cxnMonitor)
client, err := mongo.Connect(clientOpts)

The following table describes the types of pool events that the driver emits:

Pool Event Type
Description

ConnectionPoolCreated

Created when a connection pool is created.

ConnectionPoolReady

Created when a connection pool is ready.

ConnectionPoolCleared

Created when all the connections in the pool are closed.

ConnectionPoolClosed

Created when a connection pool is closed, before the destruction of the server instance.

ConnectionCreated

Created when a connection is created, but not necessarily when it is used for an operation.

ConnectionReady

Created after a connection completes a handshake and is ready to be used for operations.

ConnectionClosed

Created when a connection is closed.

ConnectionCheckOutStarted

Created when an operation attempts to acquire a connection for execution.

ConnectionCheckOutFailed

Created when an operation cannot acquire a connection for execution.

ConnectionCheckedOut

Created when an operation successfully acquires a connection for execution.

ConnectionCheckedIn

Created when a connection is checked back into the pool after an operation is executed.

The following sections show sample output for each type of connection pool monitoring event.

*event.PoolEvent
{
"type": "ConnectionPoolCreated",
"address": "...",
"connectionId": 0,
"options": {
"maxPoolSize": 100,
"minPoolSize": 0,
"maxIdleTimeMS": 0
},
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionPoolReady",
"address": "...",
"connectionId": 0,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionPoolCleared",
"address": "...",
"connectionId": 0,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionPoolClosed",
"address": "...",
"connectionId": 0,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionCreated",
"address": "...",
"connectionId": 1,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionReady",
"address": "...",
"connectionId": 1,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionClosed",
"address": "...",
"connectionId": 1,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionCheckOutStarted",
"address": "...",
"connectionId": 0,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionCheckOutFailed",
"address": "...",
"connectionId": 0,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionCheckedOut",
"address": "...",
"connectionId": 1,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}
*event.PoolEvent
{
"type": "ConnectionCheckedIn",
"address": "...",
"connectionId": 1,
"options": null,
"reason": "",
"serviceId": null,
"error": null
}

To learn more about monitoring a MongoDB deployment, see the How to Monitor MongoDB article.

To learn more about connecting to MongoDB, see the Connection Guide.

To learn more about performing MongoDB operations, see the CRUD Operations guides.

To learn more about the methods and types mentioned in this guide, see the following API documentation:

Back

Monitoring & Logging