react-native-debug-toolkit
Version:
A simple yet powerful debugging toolkit for React Native with a convenient floating UI for development
70 lines (59 loc) • 2.2 kB
JavaScript
const MAX_LOGS = 200; // Max number of console logs to store
const logs = [];
const originalConsole = {}; // Store original console methods
const _interceptConsole = () => {
const levels = ['log', 'info', 'warn', 'error'];
levels.forEach(level => {
if (typeof console[level] === 'function') { // Check if it's actually a function
originalConsole[level] = console[level]; // Store original
console[level] = (...args) => {
// Call original console method first
originalConsole[level].apply(console, args); // Use apply for proper context
// Add log entry
if (logs.length >= MAX_LOGS) {
logs.shift(); // Remove the oldest log if limit is reached
}
// Store log data
logs.push({
timestamp: new Date(),
level: level,
data: args, // Store all arguments passed to console[level]
});
// TODO: Notify UI if needed
};
}
});
};
const _restoreConsole = () => {
Object.keys(originalConsole).forEach(level => {
if (originalConsole[level]) {
console[level] = originalConsole[level];
delete originalConsole[level]; // Clean up stored method
}
});
};
const setup = () => {
_interceptConsole();
};
const getData = () => {
return logs;
};
const cleanup = () => {
_restoreConsole();
logs.length = 0; // More efficient way to clear array
};
// Factory function remains similar but uses the module-level functions
export const createConsoleLogFeature = () => {
// Ensure setup is only called once if multiple features might be created (though unlikely for console)
// A simple flag could work here if needed, but maybe setup belongs in the main toolkit init.
return {
name: 'console',
label: 'Console Logs',
setup: setup, // Reference module-level function
getData: getData, // Reference module-level function
cleanup: cleanup, // Reference module-level function
};
};
// Note: This refactor removes the class structure entirely, relying on module scope
// for the "singleton" nature. Decide if this fits the overall pattern of other features.
// The original class-based singleton is also perfectly valid.