diff options
author | Aaron LI <aaronly.me@outlook.com> | 2016-11-09 20:21:22 +0800 |
---|---|---|
committer | Aaron LI <aaronly.me@outlook.com> | 2016-11-09 20:21:22 +0800 |
commit | 3113e2809249e1fa9a1c71f3e210d4d74ae47502 (patch) | |
tree | f2c160b13fcda8a98f022424f9bf1b6538c685cf | |
parent | 71242718eb9d8ed920ac2e70677ae54bf3d140ea (diff) | |
download | fg21sim-3113e2809249e1fa9a1c71f3e210d4d74ae47502.tar.bz2 |
webui: Add "WebSocketLogHandler" to push log to client through WebSocket
-rw-r--r-- | fg21sim/webui/loghandler.py | 61 |
1 files changed, 61 insertions, 0 deletions
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 <liweitianux@live.com> +# 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": <formatted-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) |