我正在编写一个websocket客户端,每隔几秒左右就会收到更新,利用扭曲的高速公路。我使用多个观察者成功记录数据,但是我想使用我收到的部分消息发送到数据帧(并最终实时绘图)。我的假设是我可以记录变量以及类似文件的对象,但我无法弄清楚如何做到这一点。实现这一目标的正确方法是什么。
我已经非常彻底地阅读了当前和传统扭曲记录器的文档:
twisted.log https://twistedmatrix.com/documents/current/core/howto/logging.html
twisted.logger https://twistedmatrix.com/documents/current/core/howto/logger.html
在我的代码中,我尝试使用新的twisted.logger包中引用的zope.interface和@provider来创建自定义日志观察器,但到目前为止,即使获得自定义日志观察器进行打印也没有运气,让单独甚至将数据发送到变量。
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
from twisted.logger import (globalLogBeginner, Logger, globalLogPublisher,
jsonFileLogObserver, ILogObserver)
import sys
import io
import json
from pandas import DataFrame
def loggit(message):
log.info("Echo: {message!r}", message=message)
class ClientProtocol(WebSocketClientProtocol):
def onConnect(self, response):
print("Server connected: {0}".format(response.peer))
def initMessage(self):
message_data = {}
message_json = json.dumps(message_data)
print "sendMessage: " + message_json
self.sendMessage(message_json)
def onOpen(self):
print "onOpen calls initMessage()"
self.initMessage()
def onMessage(self, msg, binary, df):
loggit(msg)
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
if __name__ == '__main__':
factory = WebSocketClientFactory("wss://ws-feed.whatever.com")
factory.protocol = ClientProtocol
@provider(ILogObserver)
def customObserver(whatgoeshere?):
print event
observers = [jsonFileLogObserver(io.open("loga.json", "a")),
jsonFileLogObserver(io.open("logb.json", "a")), customObserver(Whatgoeshere?)]
log = Logger()
globalLogBeginner.beginLoggingTo(observers)
connectWS(factory)
reactor.run()
答案 0 :(得分:0)
日志观察者只是一个可调用对象,它接受包含日志消息中所有值的字典。
这意味着您可以拥有一个类的实例,其中__call__
方法使用@zope.interface.implementer(ILogObserver)
修饰,或者使用@zope.interface.provider(ILogObserver)
修饰的函数,可以执行该角色。
这是一些代码的示例,它将一些值记录到文本文件,JSON文件和内存中的统计信息收集器中,这些收集器可以实时汇总。
import io
from zope.interface import implementer
from twisted.logger import (globalLogBeginner, Logger, jsonFileLogObserver,
ILogObserver, textFileLogObserver)
class Something(object):
log = Logger()
def doSomething(self, value):
self.log.info("Doing something to {value}",
value=value)
@implementer(ILogObserver)
class RealTimeStatistics(object):
def __init__(self):
self.stats = []
def __call__(self, event):
if 'value' in event:
self.stats.append(event['value'])
def reportCurrent(self):
print("Current Sum Is: " + repr(sum(self.stats)))
if __name__ == "__main__":
stats = RealTimeStatistics()
globalLogBeginner.beginLoggingTo([
jsonFileLogObserver(io.open("log1.json", "ab")),
textFileLogObserver(io.open("log2.txt", "ab")),
stats, # here we pass our log observer
], redirectStandardIO=False)
something = Something()
something.doSomething(1)
something.doSomething(2)
something.doSomething(3)
stats.reportCurrent()