BlueGit

timfa questward

Files

questward / server / src / logging / consoleCapture.js

consoleCapture.js

consoleCapture.js 1.4 KiB Download Raw
1/**
2 * Capture console output into a ring buffer and fan out to subscribers (editor).
3 */
4
5const MAX_LINES = 2500;
6
7/** @type {Array<{ t: number, level: string, text: string }>} */
8const lines = [];
9/** @type {Set<(entry: { t: number, level: string, text: string }) => void>} */
10const listeners = new Set();
11let hooked = false;
12
13function formatArgs (args)
14{
15 return args.map((arg) =>
16 {
17 if (typeof arg === "string")
18 { return arg; }
19 try
20 { return JSON.stringify(arg); }
21 catch
22 { return String(arg); }
23 }).join(" ");
24}
25
26function push (level, args)
27{
28 const entry = {
29 t: Date.now(),
30 level,
31 text: formatArgs(args)
32 };
33 lines.push(entry);
34 if (lines.length > MAX_LINES)
35 { lines.splice(0, lines.length - MAX_LINES); }
36 for (const listener of listeners)
37 {
38 try
39 { listener(entry); }
40 catch
41 { /* ignore subscriber errors */ }
42 }
43}
44
45export function hookConsoleCapture ()
46{
47 if (hooked)
48 { return; }
49 hooked = true;
50 for (const level of ["log", "info", "warn", "error", "debug"])
51 {
52 const original = console[level]?.bind(console);
53 if (!original)
54 { continue; }
55 console[level] = (...args) =>
56 {
57 push(level === "log" ? "info" : level, args);
58 original(...args);
59 };
60 }
61}
62
63export function getConsoleSnapshot (limit = 500)
64{
65 const n = Math.max(1, Math.min(MAX_LINES, limit | 0 || 500));
66 return lines.slice(-n);
67}
68
69export function subscribeConsole (listener)
70{
71 listeners.add(listener);
72 return () => listeners.delete(listener);
73}