PIntag
PIntag

Reputation: 962

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

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?

Upvotes: 2

Views: 4290

Answers (2)

Bob Lee
Bob Lee

Reputation: 27

Now, the redis library already included the monitor support itself. https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L3422

Upvotes: 1

Sripathi Krishnan
Sripathi Krishnan

Reputation: 31528

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

Note :

  1. I adapted this from the PubSub class in redis-py. See client.py
  2. This does not parse the response, but that should be simple enough
  3. 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)


Upvotes: 10

Related Questions