如何在Twisted / Autobahn中登录变量或写入向变量发送消息的观察者



我正在编写一个websocket客户端,它将每隔几秒钟左右使用autobahn与twisted接收更新。我使用多个观察者成功地记录了数据,但是我想使用接收到的部分消息发送到数据帧(并最终实时绘图)。我的假设是,我可以记录变量以及类文件对象,但我不知道如何做到这一点。正确的方法是什么?

我已经非常彻底地阅读了当前和遗留的扭曲记录器的文档:

twisted.log https://twistedmatrix.com/documents/current/core/howto/logging.html
扭曲的。记录器https://twistedmatrix.com/documents/current/core/howto/logger.html

在我的代码中,我尝试使用zope.interface和@provider,如在新的twisted中引用的。Logger包创建自定义日志观察器,但到目前为止还没有获得一个自定义日志观察器来打印,更不用说将数据发送到变量了。

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()

日志观察者只是一个可调用的对象,它接受一个包含日志消息中所有值的字典。

这意味着你可以有一个类的实例,用@zope.interface.implementer(ILogObserver)装饰__call__方法,或者用@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()

相关内容

  • 没有找到相关文章

最新更新