import os, sys, types
import zmq, logging
import time
class ZMQPUBHandler(logging.Handler):
def __init__(self, host, port):
logging.Handler.__init__(self)
ctx = zmq.Context(1,1)
self.sock = ctx.socket(zmq.PUB)
self.sock.bind('tcp://%s:%s' %(host, port))
def emit(self, record):
"""
Emit a record.
If a formatter is specified, it is used to format the record.
The record is then written to the stream with a trailing newline
[N.B. this may be removed depending on feedback]. If exception
information is present, it is formatted using
traceback.print_exception and appended to the stream.
"""
try:
msg = self.format(record)
fs = "%s\n"
if not hasattr(types, "UnicodeType"): #if no unicode support...
self.sock.send(fs % msg, zmq.NOBLOCK)
else:
try:
self.sock.send(fs % msg, zmq.NOBLOCK)
except UnicodeError:
self.sock.send(fs % msg.encode("UTF-8"), zmq.NOBLOCK)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def main():
#订阅
host = sys.argv[1]
ctx = zmq.Context(1, 1)
sock = ctx.socket(zmq.SUB)
sock.setsockopt(zmq.SUBSCRIBE, '')
sock.connect('tcp://%s:55555' % host)
while 1:
msg = sock.recv(zmq.NOBLOCK)
if msg:
print msg,
else:
time.sleep(0.1)
if __name__ == '__main__':
main()
import zmq, logging
import time
class ZMQPUBHandler(logging.Handler):
def __init__(self, host, port):
logging.Handler.__init__(self)
ctx = zmq.Context(1,1)
self.sock = ctx.socket(zmq.PUB)
self.sock.bind('tcp://%s:%s' %(host, port))
def emit(self, record):
"""
Emit a record.
If a formatter is specified, it is used to format the record.
The record is then written to the stream with a trailing newline
[N.B. this may be removed depending on feedback]. If exception
information is present, it is formatted using
traceback.print_exception and appended to the stream.
"""
try:
msg = self.format(record)
fs = "%s\n"
if not hasattr(types, "UnicodeType"): #if no unicode support...
self.sock.send(fs % msg, zmq.NOBLOCK)
else:
try:
self.sock.send(fs % msg, zmq.NOBLOCK)
except UnicodeError:
self.sock.send(fs % msg.encode("UTF-8"), zmq.NOBLOCK)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def main():
#订阅
host = sys.argv[1]
ctx = zmq.Context(1, 1)
sock = ctx.socket(zmq.SUB)
sock.setsockopt(zmq.SUBSCRIBE, '')
sock.connect('tcp://%s:55555' % host)
while 1:
msg = sock.recv(zmq.NOBLOCK)
if msg:
print msg,
else:
time.sleep(0.1)
if __name__ == '__main__':
main()