DZone
Database Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Database Zone > Monitoring MongoDB Driver Events in Motor

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.

A. Jesse Jiryu Davis user avatar by
A. Jesse Jiryu Davis
·
Feb. 22, 17 · Database Zone · Tutorial
Like (1)
Save
Tweet
3.83K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • A complete example with Motor
  • PyMongo’s monitoring API
  • The Command Monitoring Spec for all MongoDB Drivers
  • The Topology Monitoring Spec for all MongoDB Drivers

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


Driver (software) MongoDB Event

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.

Popular on DZone

  • Modern Application Security Requires Defense in Depth
  • 5 Ways to Optimize Your CQL Queries for Performance
  • 5 Myths of Kubernetes
  • Implementing Microservices Architectures

Comments

Database Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo