Record console calls for diagnostics without silencing devtools
A mobile web app has a hidden “Send diagnostics” button. When a user taps it, support wants the recent console output attached to the bug report, without changing any of the app’s existing logging calls and without hiding the logs from the developer tools.
Implement recordConsole(methods). It starts recording calls to the given console methods and returns a recorder.
const recorder = recordConsole(methods = ['log']);
recorder.entries(); // => Array<{ method: string, args: unknown[] }>
recorder.clear(); // forget recorded calls, keep recording
recorder.restore(); // stop recording and put the original methods back
methods is an array of console method names, such as ['log', 'warn', 'error']. It defaults to ['log']. Names listed more than once are recorded once per call. Names that are not functions on console are ignored.recordConsole returns, calling one of those methods (for example console.warn('low disk', 12)) records an entry { method: 'warn', args: ['low disk', 12] }.console as this and the same arguments. The wrapper returns whatever that method returns.args is a new array holding the original argument values (objects are kept by reference, not copied).entries() returns a new array of the recorded entries in call order, across all recorded methods. Changing the returned array does not affect the recorder.clear() empties the history. Recording continues.restore() puts back exactly the functions that were on console when recordConsole was called, and the recorder never records again. Calling it twice is safe. entries() still returns what was recorded.const recorder = recordConsole(['log', 'warn']);
console.log('boot', { build: 42 }); // still printed in the dev tools
console.warn('slow network');
console.info('not recorded');
recorder.entries();
// => [
// { method: 'log', args: ['boot', { build: 42 }] },
// { method: 'warn', args: ['slow network'] },
// ]
recorder.clear();
console.log('after clear');
recorder.entries(); // => [{ method: 'log', args: ['after clear'] }]
recorder.restore();
console.log('not recorded');
recorder.entries(); // => [{ method: 'log', args: ['after clear'] }]