-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlog-tap.js
More file actions
76 lines (70 loc) · 2.39 KB
/
Copy pathlog-tap.js
File metadata and controls
76 lines (70 loc) · 2.39 KB
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
// Reversible console wrap + window error taps -> subscribers.
const LEVELS = ['log', 'info', 'warn', 'error', 'debug'];
export class LogTap {
constructor() {
this.installed = false;
this.originals = {};
this.subscribers = new Set();
this._winErrorHandler = null;
this._winRejectionHandler = null;
}
install() {
if (this.installed) return;
for (const level of LEVELS) {
const orig = console[level];
this.originals[level] = orig;
console[level] = (...args) => {
try { this._fanout({ level, args }); } catch {}
return orig.apply(console, args);
};
}
this._winErrorHandler = (ev) => {
try { this._fanout({ level: 'error', args: [ev.error || ev.message], source: 'window.error' }); } catch {}
};
this._winRejectionHandler = (ev) => {
try { this._fanout({ level: 'error', args: [ev.reason], source: 'unhandledrejection' }); } catch {}
};
window.addEventListener('error', this._winErrorHandler);
window.addEventListener('unhandledrejection', this._winRejectionHandler);
this.installed = true;
}
uninstall() {
if (!this.installed) return;
for (const level of LEVELS) {
console[level] = this.originals[level];
}
if (this._winErrorHandler) window.removeEventListener('error', this._winErrorHandler);
if (this._winRejectionHandler) window.removeEventListener('unhandledrejection', this._winRejectionHandler);
this.originals = {};
this._winErrorHandler = null;
this._winRejectionHandler = null;
this.installed = false;
}
// filterFn optional; false drops the entry.
subscribe(filterFn, callback) {
const sub = { filterFn, callback };
this.subscribers.add(sub);
return () => this.subscribers.delete(sub);
}
_fanout({ level, args, source }) {
if (this.subscribers.size === 0) return;
const entry = {
level,
timestamp: new Date().toISOString(),
source: source || 'console',
message: args.map(stringifyArg).join(' '),
};
for (const sub of this.subscribers) {
try {
if (sub.filterFn && !sub.filterFn(entry)) continue;
sub.callback(entry);
} catch {}
}
}
}
function stringifyArg(a) {
if (a == null) return String(a);
if (typeof a === 'string') return a;
if (a instanceof Error) return `${a.name}: ${a.message}\n${a.stack || ''}`;
try { return JSON.stringify(a); } catch { return String(a); }
}