forked from electrode-io/electrode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog-view.js
355 lines (302 loc) · 8.86 KB
/
log-view.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
"use strict";
/* eslint-disable no-magic-numbers, no-use-before-define, no-unused-vars */
/* eslint-disable no-console, max-statements, no-param-reassign, complexity */
/* global window, document, EventSource, fetch */
let logStream;
let logStreamReconnectDelay = 5000;
let logStreamReconnectTimer;
let debugStreamEvents;
function startLogStream() {
const close = () => {
if (logStream) {
logStream.close();
}
logStream = null;
};
close();
clearTimeout(logStreamReconnectTimer);
logStreamReconnectTimer = null;
logStream = new EventSource("/__electrode_dev/stream-logs");
logStream.addEventListener("log-stream", e => {
if (debugStreamEvents) {
console.log("stream event", e);
}
const data = JSON.parse(e.data);
updateLogs(data);
});
logStream.addEventListener("open", e => {
console.log("log stream opened");
logStreamReconnectDelay = 5000;
});
logStream.addEventListener("error", (e, a) => {
console.log("log stream connect error", e);
close();
logStreamReconnectTimer = setTimeout(() => {
console.log("trying to reconnect log stream", logStreamReconnectDelay);
startLogStream();
if (logStreamReconnectDelay < 1000 * 60) {
logStreamReconnectDelay = Math.floor(logStreamReconnectDelay * 1.5);
} else {
logStreamReconnectDelay = 1000 * 60;
}
}, logStreamReconnectDelay);
});
}
setTimeout(startLogStream, 100);
const logDisplayElement = document.getElementById("logs");
// this is the ID of last received and displayed entry
// when received new entries, only those with ID after this are kept
let lastEntryId = { ts: 0, tx: 0 };
function compareEntryId(a, b) {
if (a.ts === b.ts) {
return (a.tx || 0) - (b.tx || 0);
}
return a.ts - b.ts;
}
function stringifyEntryId(entryId) {
return entryId.tx ? `${entryId.ts},${entryId.tx}` : `${entryId.ts}`;
}
// track logs from across restarted dev servers
let instanceId = -1;
const defaultLevelSelections = {
error: true,
warn: true,
info: true,
http: true,
verbose: true,
debug: true,
silly: true
};
class HashValues {
constructor() {
this.setFromUrl();
}
setFromUrl() {
const hash = window.location.hash;
if (hash) {
this._hash = hash
.substr(1)
.split("&")
.reduce((acc, val) => {
const kvp = val.split("=");
if (kvp.length === 2 && kvp[0]) {
acc[kvp[0]] = kvp[1];
}
return acc;
}, {});
} else {
this._hash = {};
}
}
toUrl() {
const str = Object.keys(this._hash)
.sort()
.map(k => `${k}=${this._hash[k]}`)
.join("&");
return str ? "#" + str : "";
}
changed() {
const str = this.toUrl();
return str !== window.location.hash;
}
add(values) {
this._hash = { ...this._hash, ...values };
this.update();
}
remove(values) {
[].concat(values).forEach(k => delete this._hash[k]);
this.update();
}
update() {
if (this._updateTimer) {
return;
}
this._updateTimer = setTimeout(() => {
this._updateTimer = undefined;
const str = this.toUrl();
if (str !== window.location.hash) {
window.history.pushState(
this._hash,
document.title,
window.location.pathname + window.location.search + str
);
}
}, 10);
}
getInt(name, defaultVal = 0) {
const int = parseInt(this._hash[name], 10);
if (Number.isInteger(int)) {
return int;
}
return defaultVal;
}
get(name) {
return this._hash[name];
}
has(name) {
return this._hash.hasOwnProperty(name);
}
keys() {
return Object.keys(this._hash);
}
}
const hashVal = new HashValues();
function getLevelSelections() {
const levels = Object.keys(defaultLevelSelections);
const levelSelections = levels.reduce((acc, level) => {
const checkBox = document.getElementById("level." + level);
acc[level] = checkBox.checked;
return acc;
}, {});
return { ...defaultLevelSelections, ...levelSelections };
}
function levelChangeHandler() {
refreshLogs(getLevelSelections(), false);
}
function refreshLogs(levelSelections, scrollToEnd = true) {
levelSelections = levelSelections || getLevelSelections();
for (let line = logDisplayElement.firstChild; line !== null; line = line.nextSibling) {
const lvl = line.getAttribute("lvl");
if (!levelSelections[lvl]) {
line.setAttribute("class", "hide");
} else {
line.removeAttribute("class");
}
}
const offLevels = Object.keys(levelSelections).reduce((acc, k) => {
if (!levelSelections[k]) {
acc[k] = false;
}
return acc;
}, {});
hashVal.remove(Object.keys(levelSelections));
hashVal.add(offLevels);
}
function clearLogs() {
while (logDisplayElement.lastChild) {
logDisplayElement.removeChild(logDisplayElement.lastChild);
}
}
function wipeLogs() {
const last = logDisplayElement.lastChild;
console.log("wipe logs, last", last);
if (last) {
const entryId = last.getAttribute("entryId");
lastEntryId = parseEntryId(entryId);
hashVal.add({ entryId, id: instanceId });
} else {
lastEntryId = { ts: Date.now(), tx: 0 };
hashVal.add({ entryId: `${Date.now()}`, id: instanceId });
}
clearLogs();
}
async function updateLogs(data, levelSelections, scrollToEnd = true) {
levelSelections = levelSelections || getLevelSelections();
if (hashVal.has("id")) {
instanceId = hashVal.getInt("id");
}
let newLogs = data.logs;
// different instanceId means server would've returned all logs
if (data.instanceId && instanceId !== data.instanceId) {
if (hashVal.has("entryId") && instanceId > 0) {
hashVal.remove(["entryId", "id"]);
lastEntryId = { ts: 0 };
}
instanceId = data.instanceId;
// instance ID completely different, need to start a clean slate log
clearLogs();
} else {
// filter received logs by timestamp, only the ones after current timestamp are kept
newLogs = data.logs.filter(l => {
return compareEntryId(l, lastEntryId) > 0;
});
}
const bounding = logDisplayElement.getBoundingClientRect();
// check if bottom is in view (< -25 to account for our top margin of 30px)
const bottomInView =
bounding.bottom - (window.innerHeight || document.documentElement.clientHeight) < -25;
if (newLogs.length > 0) {
newLogs.forEach(event => {
const newLine = document.createElement("div");
newLine.setAttribute("lvl", event.level);
newLine.setAttribute("entryId", stringifyEntryId(event));
if (!levelSelections[event.level]) {
newLine.setAttribute("class", "hide");
}
newLine.innerHTML = event.message;
logDisplayElement.appendChild(newLine);
});
}
// console.log(bounding.bottom, window.innerHeight);
// only auto scroll to end if bottom was already visible in view
if (scrollToEnd && bottomInView) {
setTimeout(() => window.scrollTo(0, document.body.scrollHeight - 30), 0);
}
}
async function displayLogs(levelSelections, scrollToEnd = true) {
levelSelections = levelSelections || getLevelSelections();
if (hashVal.has("id")) {
instanceId = hashVal.getInt("id");
}
// if we have no logs displaying, we need to fetch all logs from start index
// else we just fetch new logs since last fetch
let entryId;
if (logDisplayElement.childElementCount === 0) {
entryId = stringifyEntryId(lastEntryId);
} else {
const children = logDisplayElement.children;
const last = children[children.length - 1];
entryId = last.getAttribute("entryId");
}
const logResponse = await fetch(
`/__electrode_dev/log-events?entryId=${entryId}&id=${instanceId}`
);
const data = await logResponse.json();
updateLogs(data, levelSelections, scrollToEnd);
}
function updateLevelCheckboxes() {
Object.keys(defaultLevelSelections).forEach(k => {
const elem = document.getElementById(`level.${k}`);
if (elem) {
elem.checked = hashVal.get(k) !== "false";
}
});
}
function parseEntryId(str) {
if (str.indexOf(",") > 0) {
const parts = str.split(",");
return {
ts: parseInt(parts[0]),
tx: parseInt(parts[1])
};
}
return { ts: parseInt(str), tx: 0 };
}
window.addEventListener(
"hashchange",
() => {
if (hashVal.changed()) {
hashVal.setFromUrl();
updateLevelCheckboxes();
const entryId = parseEntryId(hashVal.get("entryId") || "0");
// const start = hashVal.getInt("start");
if (compareEntryId(entryId, lastEntryId) !== 0) {
hashVal.add({ entryId: stringifyEntryId(entryId) });
clearLogs();
lastEntryId = entryId;
displayLogs();
} else {
refreshLogs();
}
}
},
false
);
window.addEventListener("keypress", function(event) {
if (event.ctrlKey && event.code === "KeyK") {
wipeLogs();
}
});
lastEntryId = parseEntryId(hashVal.get("entryId") || "0");
updateLevelCheckboxes();
// setTimeout(displayLogs, 10);