-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconsoleCatcher.ts
More file actions
96 lines (80 loc) · 2.67 KB
/
consoleCatcher.ts
File metadata and controls
96 lines (80 loc) · 2.67 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* @file Module for intercepting console logs with stack trace capture
*/
import type { ConsoleLogEvent } from '@hawk.so/types';
const createConsoleCatcher = (): {
initConsoleCatcher: () => void;
addErrorEvent: (event: ErrorEvent | PromiseRejectionEvent) => void;
getConsoleLogStack: () => ConsoleLogEvent[];
} => {
const MAX_LOGS = 20;
const consoleOutput: ConsoleLogEvent[] = [];
let isInitialized = false;
const addToConsoleOutput = (logEvent: ConsoleLogEvent): void => {
if (consoleOutput.length >= MAX_LOGS) {
consoleOutput.shift();
}
consoleOutput.push(logEvent);
};
const createConsoleEventFromError = (
event: ErrorEvent | PromiseRejectionEvent
): ConsoleLogEvent => {
if (event instanceof ErrorEvent) {
return {
method: 'error',
timestamp: new Date(),
type: event.error?.name || 'Error',
message: event.error?.message || event.message,
stack: event.error?.stack || '',
fileLine: event.filename
? `${event.filename}:${event.lineno}:${event.colno}`
: '',
};
}
return {
method: 'error',
timestamp: new Date(),
type: 'UnhandledRejection',
message: event.reason?.message || String(event.reason),
stack: event.reason?.stack || '',
fileLine: '',
};
};
return {
initConsoleCatcher(): void {
if (isInitialized) {
return;
}
isInitialized = true;
const consoleMethods: string[] = ['log', 'warn', 'error', 'info', 'debug'];
consoleMethods.forEach((method) => {
if (typeof window.console[method] !== 'function') {
return;
}
const oldFunction = window.console[method].bind(window.console);
window.console[method] = function (...args: unknown[]): void {
const stack = new Error().stack?.split('\n').slice(2).join('\n') || '';
const logEvent: ConsoleLogEvent = {
method,
timestamp: new Date(),
type: method,
message: args.map((arg) => typeof arg === 'string' ? arg : JSON.stringify(arg)).join(' '),
stack,
fileLine: stack.split('\n')[0]?.trim(),
};
addToConsoleOutput(logEvent);
oldFunction(...args);
};
});
},
addErrorEvent(event: ErrorEvent | PromiseRejectionEvent): void {
const logEvent = createConsoleEventFromError(event);
addToConsoleOutput(logEvent);
},
getConsoleLogStack(): ConsoleLogEvent[] {
return [ ...consoleOutput ];
},
};
};
const consoleCatcher = createConsoleCatcher();
export const { initConsoleCatcher, getConsoleLogStack, addErrorEvent } = consoleCatcher;