forked from iplayfast/zoidberg
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebsocket_log_handler.py
35 lines (30 loc) · 1.11 KB
/
websocket_log_handler.py
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
import json
from datetime import datetime, timedelta
from collections import deque
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
if isinstance(obj, timedelta):
f = obj.total_seconds()
mins = f // 60
return "%02d:%06.03f" % (mins, f % 60)
return json.JSONEncoder.default(self, obj)
class WebsocketLogHandler:
def __init__(self):
self.started = datetime.utcnow()
self.queue = deque(maxlen=1000)
self.websockets = set()
def emit(self, record):
# messenger.Messages.logging
timestamp = datetime.utcfromtimestamp(record.header.stamp.secs)
buf = json.dumps(dict(
action="log-entry",
created=timestamp,
uptime=timestamp - self.started,
file=record.file.replace('.py', ''),
message=record.msg,
severity=record.level), cls=MyEncoder)
self.queue.append(buf)
for websocket in self.websockets:
websocket.send(buf)