monitoring
– Tools for monitoring driver events.¶
Tools to monitor driver events.
New in version 3.1.
Attention
Starting in PyMongo 3.11, the monitoring classes outlined below
are included in the PyMongo distribution under the
event_loggers
submodule.
Use register()
to register global listeners for specific events.
Listeners must inherit from one of the abstract classes below and implement
the correct functions for that class.
For example, a simple command logger might be implemented like this:
import logging
from pymongo import monitoring
class CommandLogger(monitoring.CommandListener):
def started(self, event):
logging.info("Command {0.command_name} with request id "
"{0.request_id} started on server "
"{0.connection_id}".format(event))
def succeeded(self, event):
logging.info("Command {0.command_name} with request id "
"{0.request_id} on server {0.connection_id} "
"succeeded in {0.duration_micros} "
"microseconds".format(event))
def failed(self, event):
logging.info("Command {0.command_name} with request id "
"{0.request_id} on server {0.connection_id} "
"failed in {0.duration_micros} "
"microseconds".format(event))
monitoring.register(CommandLogger())
Server discovery and monitoring events are also available. For example:
class ServerLogger(monitoring.ServerListener):
def opened(self, event):
logging.info("Server {0.server_address} added to topology "
"{0.topology_id}".format(event))
def description_changed(self, event):
previous_server_type = event.previous_description.server_type
new_server_type = event.new_description.server_type
if new_server_type != previous_server_type:
# server_type_name was added in PyMongo 3.4
logging.info(
"Server {0.server_address} changed type from "
"{0.previous_description.server_type_name} to "
"{0.new_description.server_type_name}".format(event))
def closed(self, event):
logging.warning("Server {0.server_address} removed from topology "
"{0.topology_id}".format(event))
class HeartbeatLogger(monitoring.ServerHeartbeatListener):
def started(self, event):
logging.info("Heartbeat sent to server "
"{0.connection_id}".format(event))
def succeeded(self, event):
# The reply.document attribute was added in PyMongo 3.4.
logging.info("Heartbeat to server {0.connection_id} "
"succeeded with reply "
"{0.reply.document}".format(event))
def failed(self, event):
logging.warning("Heartbeat to server {0.connection_id} "
"failed with error {0.reply}".format(event))
class TopologyLogger(monitoring.TopologyListener):
def opened(self, event):
logging.info("Topology with id {0.topology_id} "
"opened".format(event))
def description_changed(self, event):
logging.info("Topology description updated for "
"topology id {0.topology_id}".format(event))
previous_topology_type = event.previous_description.topology_type
new_topology_type = event.new_description.topology_type
if new_topology_type != previous_topology_type:
# topology_type_name was added in PyMongo 3.4
logging.info(
"Topology {0.topology_id} changed type from "
"{0.previous_description.topology_type_name} to "
"{0.new_description.topology_type_name}".format(event))
# The has_writable_server and has_readable_server methods
# were added in PyMongo 3.4.
if not event.new_description.has_writable_server():
logging.warning("No writable servers available.")
if not event.new_description.has_readable_server():
logging.warning("No readable servers available.")
def closed(self, event):
logging.info("Topology with id {0.topology_id} "
"closed".format(event))
Connection monitoring and pooling events are also available. For example:
class ConnectionPoolLogger(ConnectionPoolListener):
def pool_created(self, event):
logging.info("[pool {0.address}] pool created".format(event))
def pool_cleared(self, event):
logging.info("[pool {0.address}] pool cleared".format(event))
def pool_closed(self, event):
logging.info("[pool {0.address}] pool closed".format(event))
def connection_created(self, event):
logging.info("[pool {0.address}][conn #{0.connection_id}] "
"connection created".format(event))
def connection_ready(self, event):
logging.info("[pool {0.address}][conn #{0.connection_id}] "
"connection setup succeeded".format(event))
def connection_closed(self, event):
logging.info("[pool {0.address}][conn #{0.connection_id}] "
"connection closed, reason: "
"{0.reason}".format(event))
def connection_check_out_started(self, event):
logging.info("[pool {0.address}] connection check out "
"started".format(event))
def connection_check_out_failed(self, event):
logging.info("[pool {0.address}] connection check out "
"failed, reason: {0.reason}".format(event))
def connection_checked_out(self, event):
logging.info("[pool {0.address}][conn #{0.connection_id}] "
"connection checked out of pool".format(event))
def connection_checked_in(self, event):
logging.info("[pool {0.address}][conn #{0.connection_id}] "
"connection checked into pool".format(event))
Event listeners can also be registered per instance of
MongoClient
:
client = MongoClient(event_listeners=[CommandLogger()])
Note that previously registered global listeners are automatically included when configuring per client event listeners. Registering a new global listener will not add that listener to existing client instances.
Note
Events are delivered synchronously. Application threads block
waiting for event handlers (e.g. started()
) to
return. Care must be taken to ensure that your event handlers are efficient
enough to not adversely affect overall application performance.
Warning
The command documents published through this API are not copies. If you intend to modify them in any way you must copy them in your event handler first.
- pymongo.monitoring.register(listener)¶
Register a global event listener.
- Parameters
listener: A subclasses of
CommandListener
,ServerHeartbeatListener
,ServerListener
,TopologyListener
, orConnectionPoolListener
.
- class pymongo.monitoring.CommandListener¶
Abstract base class for command listeners.
Handles CommandStartedEvent, CommandSucceededEvent, and CommandFailedEvent.
- failed(event: pymongo.monitoring.CommandFailedEvent) None ¶
Abstract method to handle a CommandFailedEvent.
- Parameters
event: An instance of
CommandFailedEvent
.
- started(event: pymongo.monitoring.CommandStartedEvent) None ¶
Abstract method to handle a CommandStartedEvent.
- Parameters
event: An instance of
CommandStartedEvent
.
- succeeded(event: pymongo.monitoring.CommandSucceededEvent) None ¶
Abstract method to handle a CommandSucceededEvent.
- Parameters
event: An instance of
CommandSucceededEvent
.
- class pymongo.monitoring.ServerListener¶
Abstract base class for server listeners. Handles ServerOpeningEvent, ServerDescriptionChangedEvent, and ServerClosedEvent.
New in version 3.3.
- closed(event: pymongo.monitoring.ServerClosedEvent) None ¶
Abstract method to handle a ServerClosedEvent.
- Parameters
event: An instance of
ServerClosedEvent
.
- description_changed(event: pymongo.monitoring.ServerDescriptionChangedEvent) None ¶
Abstract method to handle a ServerDescriptionChangedEvent.
- Parameters
event: An instance of
ServerDescriptionChangedEvent
.
- opened(event: pymongo.monitoring.ServerOpeningEvent) None ¶
Abstract method to handle a ServerOpeningEvent.
- Parameters
event: An instance of
ServerOpeningEvent
.
- class pymongo.monitoring.ServerHeartbeatListener¶
Abstract base class for server heartbeat listeners.
Handles ServerHeartbeatStartedEvent, ServerHeartbeatSucceededEvent, and ServerHeartbeatFailedEvent.
New in version 3.3.
- failed(event: pymongo.monitoring.ServerHeartbeatFailedEvent) None ¶
Abstract method to handle a ServerHeartbeatFailedEvent.
- Parameters
event: An instance of
ServerHeartbeatFailedEvent
.
- started(event: pymongo.monitoring.ServerHeartbeatStartedEvent) None ¶
Abstract method to handle a ServerHeartbeatStartedEvent.
- Parameters
event: An instance of
ServerHeartbeatStartedEvent
.
- succeeded(event: pymongo.monitoring.ServerHeartbeatSucceededEvent) None ¶
Abstract method to handle a ServerHeartbeatSucceededEvent.
- Parameters
event: An instance of
ServerHeartbeatSucceededEvent
.
- class pymongo.monitoring.TopologyListener¶
Abstract base class for topology monitoring listeners. Handles TopologyOpenedEvent, TopologyDescriptionChangedEvent, and TopologyClosedEvent.
New in version 3.3.
- closed(event: pymongo.monitoring.TopologyClosedEvent) None ¶
Abstract method to handle a TopologyClosedEvent.
- Parameters
event: An instance of
TopologyClosedEvent
.
- description_changed(event: pymongo.monitoring.TopologyDescriptionChangedEvent) None ¶
Abstract method to handle a TopologyDescriptionChangedEvent.
- Parameters
event: An instance of
TopologyDescriptionChangedEvent
.
- opened(event: pymongo.monitoring.TopologyOpenedEvent) None ¶
Abstract method to handle a TopologyOpenedEvent.
- Parameters
event: An instance of
TopologyOpenedEvent
.
- class pymongo.monitoring.ConnectionPoolListener¶
Abstract base class for connection pool listeners.
Handles all of the connection pool events defined in the Connection Monitoring and Pooling Specification:
PoolCreatedEvent
,PoolClearedEvent
,PoolClosedEvent
,ConnectionCreatedEvent
,ConnectionReadyEvent
,ConnectionClosedEvent
,ConnectionCheckOutStartedEvent
,ConnectionCheckOutFailedEvent
,ConnectionCheckedOutEvent
, andConnectionCheckedInEvent
.New in version 3.9.
- connection_check_out_failed(event: pymongo.monitoring.ConnectionCheckOutFailedEvent) None ¶
Abstract method to handle a
ConnectionCheckOutFailedEvent
.Emitted when the driver’s attempt to check out a connection fails.
- Parameters
event: An instance of
ConnectionCheckOutFailedEvent
.
- connection_check_out_started(event: pymongo.monitoring.ConnectionCheckOutStartedEvent) None ¶
Abstract method to handle a
ConnectionCheckOutStartedEvent
.Emitted when the driver starts attempting to check out a connection.
- Parameters
event: An instance of
ConnectionCheckOutStartedEvent
.
- connection_checked_in(event: pymongo.monitoring.ConnectionCheckedInEvent) None ¶
Abstract method to handle a
ConnectionCheckedInEvent
.Emitted when the driver checks in a Connection back to the Connection Pool.
- Parameters
event: An instance of
ConnectionCheckedInEvent
.
- connection_checked_out(event: pymongo.monitoring.ConnectionCheckedOutEvent) None ¶
Abstract method to handle a
ConnectionCheckedOutEvent
.Emitted when the driver successfully checks out a Connection.
- Parameters
event: An instance of
ConnectionCheckedOutEvent
.
- connection_closed(event: pymongo.monitoring.ConnectionClosedEvent) None ¶
Abstract method to handle a
ConnectionClosedEvent
.Emitted when a Connection Pool closes a Connection.
- Parameters
event: An instance of
ConnectionClosedEvent
.
- connection_created(event: pymongo.monitoring.ConnectionCreatedEvent) None ¶
Abstract method to handle a
ConnectionCreatedEvent
.Emitted when a Connection Pool creates a Connection object.
- Parameters
event: An instance of
ConnectionCreatedEvent
.
- connection_ready(event: pymongo.monitoring.ConnectionReadyEvent) None ¶
Abstract method to handle a
ConnectionReadyEvent
.Emitted when a Connection has finished its setup, and is now ready to use.
- Parameters
event: An instance of
ConnectionReadyEvent
.
- pool_cleared(event: pymongo.monitoring.PoolClearedEvent) None ¶
Abstract method to handle a PoolClearedEvent.
Emitted when a Connection Pool is cleared.
- Parameters
event: An instance of
PoolClearedEvent
.
- pool_closed(event: pymongo.monitoring.PoolClosedEvent) None ¶
Abstract method to handle a PoolClosedEvent.
Emitted when a Connection Pool is closed.
- Parameters
event: An instance of
PoolClosedEvent
.
- pool_created(event: pymongo.monitoring.PoolCreatedEvent) None ¶
Abstract method to handle a
PoolCreatedEvent
.Emitted when a Connection Pool is created.
- Parameters
event: An instance of
PoolCreatedEvent
.
- class pymongo.monitoring.CommandStartedEvent(command: Union[MutableMapping[str, Any], RawBSONDocument], database_name: str, request_id: int, connection_id: Tuple[str, Optional[int]], operation_id: Optional[int], service_id: Optional[bson.objectid.ObjectId] = None)¶
Event published when a command starts.
- Parameters
command: The command document.
database_name: The name of the database this command was run against.
request_id: The request id for this operation.
connection_id: The address (host, port) of the server this command was sent to.
operation_id: An optional identifier for a series of related events.
service_id: The service_id this command was sent to, or
None
.
- property command: Union[MutableMapping[str, Any], RawBSONDocument]¶
The command document.
- property connection_id: Tuple[str, Optional[int]]¶
The address (host, port) of the server this command was sent to.
- property service_id: Optional[bson.objectid.ObjectId]¶
The service_id this command was sent to, or
None
.New in version 3.12.
- class pymongo.monitoring.CommandSucceededEvent(duration: datetime.timedelta, reply: Union[MutableMapping[str, Any], RawBSONDocument], command_name: str, request_id: int, connection_id: Tuple[str, Optional[int]], operation_id: Optional[int], service_id: Optional[bson.objectid.ObjectId] = None)¶
Event published when a command succeeds.
- Parameters
duration: The command duration as a datetime.timedelta.
reply: The server reply document.
command_name: The command name.
request_id: The request id for this operation.
connection_id: The address (host, port) of the server this command was sent to.
operation_id: An optional identifier for a series of related events.
service_id: The service_id this command was sent to, or
None
.
- property connection_id: Tuple[str, Optional[int]]¶
The address (host, port) of the server this command was sent to.
- property reply: Union[MutableMapping[str, Any], RawBSONDocument]¶
The server failure document for this operation.
- property service_id: Optional[bson.objectid.ObjectId]¶
The service_id this command was sent to, or
None
.New in version 3.12.
- class pymongo.monitoring.CommandFailedEvent(duration: datetime.timedelta, failure: Union[MutableMapping[str, Any], RawBSONDocument], command_name: str, request_id: int, connection_id: Tuple[str, Optional[int]], operation_id: Optional[int], service_id: Optional[bson.objectid.ObjectId] = None)¶
Event published when a command fails.
- Parameters
duration: The command duration as a datetime.timedelta.
failure: The server reply document.
command_name: The command name.
request_id: The request id for this operation.
connection_id: The address (host, port) of the server this command was sent to.
operation_id: An optional identifier for a series of related events.
service_id: The service_id this command was sent to, or
None
.
- property connection_id: Tuple[str, Optional[int]]¶
The address (host, port) of the server this command was sent to.
- property failure: Union[MutableMapping[str, Any], RawBSONDocument]¶
The server failure document for this operation.
- property service_id: Optional[bson.objectid.ObjectId]¶
The service_id this command was sent to, or
None
.New in version 3.12.
- class pymongo.monitoring.ServerDescriptionChangedEvent(previous_description: ServerDescription, new_description: ServerDescription, *args: Any)¶
Published when server description changes.
New in version 3.3.
- property new_description: ServerDescription¶
The new
ServerDescription
.
- property previous_description: ServerDescription¶
The previous
ServerDescription
.
- property topology_id: bson.objectid.ObjectId¶
A unique identifier for the topology this server is a part of.
- class pymongo.monitoring.ServerOpeningEvent(server_address: Tuple[str, Optional[int]], topology_id: bson.objectid.ObjectId)¶
Published when server is initialized.
New in version 3.3.
- property topology_id: bson.objectid.ObjectId¶
A unique identifier for the topology this server is a part of.
- class pymongo.monitoring.ServerClosedEvent(server_address: Tuple[str, Optional[int]], topology_id: bson.objectid.ObjectId)¶
Published when server is closed.
New in version 3.3.
- property topology_id: bson.objectid.ObjectId¶
A unique identifier for the topology this server is a part of.
- class pymongo.monitoring.TopologyDescriptionChangedEvent(previous_description: TopologyDescription, new_description: TopologyDescription, *args: Any)¶
Published when the topology description changes.
New in version 3.3.
- property new_description: TopologyDescription¶
The new
TopologyDescription
.
- property previous_description: TopologyDescription¶
The previous
TopologyDescription
.
- property topology_id: bson.objectid.ObjectId¶
A unique identifier for the topology this server is a part of.
- class pymongo.monitoring.TopologyOpenedEvent(topology_id: bson.objectid.ObjectId)¶
Published when the topology is initialized.
New in version 3.3.
- property topology_id: bson.objectid.ObjectId¶
A unique identifier for the topology this server is a part of.
- class pymongo.monitoring.TopologyClosedEvent(topology_id: bson.objectid.ObjectId)¶
Published when the topology is closed.
New in version 3.3.
- property topology_id: bson.objectid.ObjectId¶
A unique identifier for the topology this server is a part of.
- class pymongo.monitoring.ServerHeartbeatStartedEvent(connection_id: Tuple[str, Optional[int]])¶
Published when a heartbeat is started.
New in version 3.3.
- class pymongo.monitoring.ServerHeartbeatSucceededEvent(duration: float, reply: pymongo.hello.Hello, connection_id: Tuple[str, Optional[int]], awaited: bool = False)¶
Fired when the server heartbeat succeeds.
New in version 3.3.
- property awaited: bool¶
Whether the heartbeat was awaited.
If true, then
duration()
reflects the sum of the round trip time to the server and the time that the server waited before sending a response.
- property connection_id: Tuple[str, Optional[int]]¶
The address (host, port) of the server this heartbeat was sent to.
- property reply: pymongo.hello.Hello¶
An instance of
Hello
.
- class pymongo.monitoring.ServerHeartbeatFailedEvent(duration: float, reply: Exception, connection_id: Tuple[str, Optional[int]], awaited: bool = False)¶
Fired when the server heartbeat fails, either with an “ok: 0” or a socket exception.
New in version 3.3.
- property awaited: bool¶
Whether the heartbeat was awaited.
If true, then
duration()
reflects the sum of the round trip time to the server and the time that the server waited before sending a response.
- class pymongo.monitoring.PoolCreatedEvent(address: Tuple[str, Optional[int]], options: Dict[str, Any])¶
Published when a Connection Pool is created.
- Parameters
address: The address (host, port) pair of the server this Pool is attempting to connect to.
New in version 3.9.
- class pymongo.monitoring.PoolClearedEvent(address: Tuple[str, Optional[int]], service_id: Optional[bson.objectid.ObjectId] = None)¶
Published when a Connection Pool is cleared.
- Parameters
address: The address (host, port) pair of the server this Pool is attempting to connect to.
service_id: The service_id this command was sent to, or
None
.
New in version 3.9.
- property address: Tuple[str, Optional[int]]¶
The address (host, port) pair of the server the pool is attempting to connect to.
- property service_id: Optional[bson.objectid.ObjectId]¶
Connections with this service_id are cleared.
When service_id is
None
, all connections in the pool are cleared.New in version 3.12.
- class pymongo.monitoring.PoolClosedEvent(address: Tuple[str, Optional[int]])¶
Published when a Connection Pool is closed.
- Parameters
address: The address (host, port) pair of the server this Pool is attempting to connect to.
New in version 3.9.
- class pymongo.monitoring.ConnectionCreatedEvent(address: Tuple[str, Optional[int]], connection_id: int)¶
Published when a Connection Pool creates a Connection object.
NOTE: This connection is not ready for use until the
ConnectionReadyEvent
is published.- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
connection_id: The integer ID of the Connection in this Pool.
New in version 3.9.
- class pymongo.monitoring.ConnectionReadyEvent(address: Tuple[str, Optional[int]], connection_id: int)¶
Published when a Connection has finished its setup, and is ready to use.
- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
connection_id: The integer ID of the Connection in this Pool.
New in version 3.9.
- class pymongo.monitoring.ConnectionClosedReason¶
An enum that defines values for reason on a
ConnectionClosedEvent
.New in version 3.9.
- ERROR = 'error'¶
The connection experienced an error, making it no longer valid.
- IDLE = 'idle'¶
The connection became stale by being idle for too long (maxIdleTimeMS).
- POOL_CLOSED = 'poolClosed'¶
The pool was closed, making the connection no longer valid.
- STALE = 'stale'¶
The pool was cleared, making the connection no longer valid.
- class pymongo.monitoring.ConnectionClosedEvent(address, connection_id, reason)¶
Published when a Connection is closed.
- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
connection_id: The integer ID of the Connection in this Pool.
reason: A reason explaining why this connection was closed.
New in version 3.9.
- property address: Tuple[str, Optional[int]]¶
The address (host, port) pair of the server this connection is attempting to connect to.
- property reason¶
A reason explaining why this connection was closed.
The reason must be one of the strings from the
ConnectionClosedReason
enum.
- class pymongo.monitoring.ConnectionCheckOutStartedEvent(address)¶
Published when the driver starts attempting to check out a connection.
- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
New in version 3.9.
- property address¶
The address (host, port) pair of the server this connection is attempting to connect to.
- class pymongo.monitoring.ConnectionCheckOutFailedReason¶
An enum that defines values for reason on a
ConnectionCheckOutFailedEvent
.New in version 3.9.
- CONN_ERROR = 'connectionError'¶
The connection check out attempt experienced an error while setting up a new connection.
- POOL_CLOSED = 'poolClosed'¶
The pool was previously closed, and cannot provide new connections.
- TIMEOUT = 'timeout'¶
The connection check out attempt exceeded the specified timeout.
- class pymongo.monitoring.ConnectionCheckOutFailedEvent(address: Tuple[str, Optional[int]], reason: str)¶
Published when the driver’s attempt to check out a connection fails.
- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
reason: A reason explaining why connection check out failed.
New in version 3.9.
- property address: Tuple[str, Optional[int]]¶
The address (host, port) pair of the server this connection is attempting to connect to.
- property reason: str¶
A reason explaining why connection check out failed.
The reason must be one of the strings from the
ConnectionCheckOutFailedReason
enum.
- class pymongo.monitoring.ConnectionCheckedOutEvent(address: Tuple[str, Optional[int]], connection_id: int)¶
Published when the driver successfully checks out a Connection.
- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
connection_id: The integer ID of the Connection in this Pool.
New in version 3.9.
- class pymongo.monitoring.ConnectionCheckedInEvent(address: Tuple[str, Optional[int]], connection_id: int)¶
Published when the driver checks in a Connection into the Pool.
- Parameters
address: The address (host, port) pair of the server this Connection is attempting to connect to.
connection_id: The integer ID of the Connection in this Pool.
New in version 3.9.