How can I mimic the redis MONITOR command in a python script using redis-py?

python, redis

Solution

Here is some minimal code to implement the monitor code in python.

Note :

- I adapted this from the PubSub class in redis-py. See client.py

- This does not parse the response, but that should be simple enough

- Doesn't do any sort of error handling

import redis        

class Monitor():
    def __init__(self, connection_pool):
        self.connection_pool = connection_pool
        self.connection = None

    def __del__(self):
        try:
            self.reset()
        except:
            pass

    def reset(self):
        if self.connection:
            self.connection_pool.release(self.connection)
            self.connection = None

    def monitor(self):
        if self.connection is None:
            self.connection = self.connection_pool.get_connection(
                'monitor', None)
        self.connection.send_command("monitor")
        return self.listen()

    def parse_response(self):
        return self.connection.read_response()

    def listen(self):
        while True:
            yield self.parse_response()

if  __name__ == '__main__':
    pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
    monitor = Monitor(pool)
    commands = monitor.monitor()

    for c in commands :
        print(c)

Problem

Unfortunately, the redis-py library does not seem to have a Monitor routine. I would like to read all of the commands received by the redis server, filter them, and then log the ones I am interested in. Does anybody have an idea of how to do this?

Original source