Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

A. Jesse Jiryu Davis: Monitoring MongoDB Driver Events In Motor

$
0
0

Image description: line drawing of a monitor lizard

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.

importloggingfrompymongoimport monitoring

classMyCommandLogger(monitoring.CommandListener):
defstarted(self, event):
logging.info("Command {0.command_name} with request id ""{0.request_id} started on server ""{0.connection_id}".format(event))

defsucceeded(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))

deffailed(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.

importsysfromtornadoimport ioloop, options, gen
frommotorimport MotorClient

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

client = MotorClient()

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

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

Watch out: PyMongo publishes notifications from a background thread, so your listeners’ callbacks are executed on that thread, not the main thread. If you want to interact with Tornado or Motor from a listener, 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


Images:


Viewing all articles
Browse latest Browse all 22462

Trending Articles