From 3113e2809249e1fa9a1c71f3e210d4d74ae47502 Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Wed, 9 Nov 2016 20:21:22 +0800 Subject: webui: Add "WebSocketLogHandler" to push log to client through WebSocket --- fg21sim/webui/loghandler.py | 61 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 fg21sim/webui/loghandler.py (limited to 'fg21sim/webui') diff --git a/fg21sim/webui/loghandler.py b/fg21sim/webui/loghandler.py new file mode 100644 index 0000000..0b457b5 --- /dev/null +++ b/fg21sim/webui/loghandler.py @@ -0,0 +1,61 @@ +# Copyright (c) 2016 Weitian LI +# MIT license + +""" +Custom logging handlers + +WebSocketLogHandler : + Send logging messages to the WebSocket as JSON-encoded string. +""" + + +import logging +import json + + +class WebSocketLogHandler(logging.Handler): + """ + Send logging messages to the WebSocket as JSON-encoded string. + + Parameters + ---------- + websocket : `~tornado.websocket.WebSocketHandler` + An `~tornado.websocket.WebSocketHandler` instance, which has + the ``write_message()`` method that will be used to send the + logging messages. + msg_type : str, optional + Set the type of the sent back message, for easier processing + by the client. + + NOTE + ---- + The message sent through the WebSocket is a JSON-encoded string + from a dictionary, e.g., + ``{"type": self.msg_type, + "action": "log", + "levelname": record.levelname, + "levelno": record.levelno, + "name": record.name, + "asctime": record.asctime, + "message": }`` + """ + def __init__(self, websocket, msg_type=None): + super().__init__() + self.websocket = websocket + self.msg_type = msg_type + + def emit(self, record): + try: + message = self.format(record) + msg = json.dumps({ + "type": self.msg_type, + "action": "log", + "levelname": record.levelname, + "levelno": record.levelno, + "name": record.name, + "asctime": record.asctime, + "message": message, + }) + self.websocket.write_message(msg) + except Exception: + self.handleError(record) -- cgit v1.2.2