我正在调试一些zeromq代码,我想记录套接字实例send / recv。换句话说,我有
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://127.0.0.1:5000")
我想以某种方式将套接字实例的send / recv记录在代码中的其他位置。
这里有什么想法吗?我不知道从哪里开始。
答案 0 :(得分:3)
以下是记录每条消息的Socket对象示例:
import logging import time import zmq class LogSocket(object): socket = None log = None name = None def __init__(self, socket, log=None, name=None): """wrap a socket so send/recv_multipart log their messages""" self.socket = socket if log is None: logging.basicConfig(level=logging.INFO) log = logging.getLogger().info self.log = log if name is None: name = s.identity or repr(s) self.name = name def send_multipart(self, msg, *args, **kwargs): self.log("%s sending: %r" % (self.name, msg)) return self.socket.send_multipart(msg, *args, **kwargs) def recv_multipart(self, *args, **kwargs): msg = self.socket.recv_multipart(*args, **kwargs) self.log("%s received: %r" % (self.name, msg)) return msg def __getattr__(self, key): return getattr(self.socket, key) ctx = zmq.Context.instance() s = ctx.socket(zmq.REQ) s.connect("tcp://127.0.0.1:5556") # wrap the zmq socket in the Logging object: # this object has exactly the same interface as s = LogSocket(s, name="REQ") for i in range(5): time.sleep(1) s.send_multipart(['hello', 'world']) reply = s.recv_multipart() # in this case, only _multipart methods are logged, so straight send/recv are not: s.send("quiet") s.recv()
在一个地方处理序列化/日志记录/身份验证等的辅助对象的一个例子是IPython中的Session object,这比这个简单的情况要复杂得多,但允许你集中化代码中的所有消息传递抽象。