Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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.

Free Resource

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

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 "
                     "{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))


Register an instance of MyCommandLogger:

monitoring.register(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!'})

ioloop.IOLoop.current().run_sync(do_insert)

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


It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate

Topics:
mongodb ,database monitoring ,database ,motor ,tutorial

Published at DZone with permission of A. Jesse Jiryu Davis, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}