Over a million developers have joined DZone.

Monitoring MongoDB Driver Events in Motor

DZone's Guide to

Monitoring MongoDB Driver Events in Motor

Want to monitor (and get notifications) for various MongoDB events, queries, and commands? Motor, and a bit of Python, can make it simple.

· Database Zone ·
Free Resource

Download the Altoros NoSQL Performance Benchmark 2018. Compare top NoSQL solutions – Couchbase Server v5.5, MongoDB v3.6, and DataStax Enterprise v6 (Cassandra).

Do you want to know every MongoDB query or command your program sends, and the server’s reply to each? How about getting a notification whenever the driver detects a primary failover, or when a new secondary joins the replica set? Over the last year, MongoDB drivers have implemented these monitoring features in all our supported programming languages. Here’s how to use monitoring in Motor, my Python async driver.

Motor wraps PyMongo, and it shares PyMongo’s API for monitoring. To receive notifications about events, you subclass one of PyMongo’s four listener classes, CommandListener, ServerListener, TopologyListener, or ServerHeartbeatListener. Let’s subclass CommandListener, so we’re notified whenever a command starts, succeeds, or fails.

import logging
from pymongo import monitoring

class MyCommandLogger(monitoring.CommandListener):
    def started(self, event):
        logging.info("Command {0.command_name} with request id "
                     "{0.request_id} started on server "

    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} "

    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} "

Register an instance of MyCommandLogger:


You can register any number of listeners, of any of the four listener types.

We only need to use PyMongo’s API here, but if you create a MotorClient its commands are monitored, the same as a PyMongo MongoClient.

import sys
from tornado import ioloop, options, gen
from motor import MotorClient

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

client = MotorClient()

async def do_insert():
    await client.test.collection.insert({'_id': 1, 'message': 'hi!'})


This logs something like:

Command insert with request id 50073 started on server ('localhost', 27017)
Command insert with request id 50073 on server ('localhost', 27017) 
  succeeded in 362 microseconds

Watch out: Your listeners’ callbacks are executed on various background threads, not the main thread. If you want to interact with Tornado or Motor from a listener callback, you must defer to the main thread using IOLoop.add_callback, which is the only thread-safe IOLoop method. Similarly, if you’re using asyncio instead of Tornado, get to the main loop with call_soon_threadsafe. I can’t think of a need for you to do this, though—it seems like logging is the only reasonable thing to do from a listener, and the Python logging module is thread-safe.

For more info, see:

That was simple, so we have time for a picture of a monitor lizard and a log:

Image Description: color photograph of a monitor lizard basking on a log

Download the whitepaper, Moving From Relational to NoSQL: How to Get Started. We’ll take you step by step through your first NoSQL project.

mongodb ,database monitoring ,database ,motor ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}