aboutsummaryrefslogtreecommitdiffstats
path: root/fg21sim/webui/loghandler.py
blob: 0b457b5da8c7f2204c41b9723cf5ec8be55e2d6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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)