aboutsummaryrefslogtreecommitdiffstats
path: root/fg21sim/webui/handlers/log.py
diff options
context:
space:
mode:
authorAaron LI <aaronly.me@outlook.com>2016-11-15 18:23:00 +0800
committerAaron LI <aaronly.me@outlook.com>2016-11-15 18:23:00 +0800
commite74ccdc92478ceb50aa2617e21f6f7eb4bc181de (patch)
treeca0832af2e1e0132edf68f756dc854fc24cc6958 /fg21sim/webui/handlers/log.py
parentbcdc84fb416820493e048fe28ca59e9090762ffb (diff)
downloadfg21sim-e74ccdc92478ceb50aa2617e21f6f7eb4bc181de.tar.bz2
webui: Place handlers under the directory "hnadlers/"
Diffstat (limited to 'fg21sim/webui/handlers/log.py')
-rw-r--r--fg21sim/webui/handlers/log.py61
1 files changed, 61 insertions, 0 deletions
diff --git a/fg21sim/webui/handlers/log.py b/fg21sim/webui/handlers/log.py
new file mode 100644
index 0000000..0b457b5
--- /dev/null
+++ b/fg21sim/webui/handlers/log.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)