Debugging in a React app with a sea of console.log statements can be a nightmare. To keep logs manageable, you can create a simple log wrapper utility that only logs messages from certain files or folders, and is easy to enable/disable when needed.
// utils/logger.js
const ENABLED_PATHS = [
'/components/MyComponent',
'/features/Auth',
];
const isLoggingEnabled = (stack) => {
return ENABLED_PATHS.some((path) => stack.includes(path));
};
export const log = (...args) => {
if (typeof window === 'undefined') return;
const stack = new Error().stack;
if (isLoggingEnabled(stack)) {
console.log(...args);
}
};
export const warn = (...args) => {
if (typeof window === 'undefined') return;
const stack = new Error().stack;
if (isLoggingEnabled(stack)) {
console.warn(...args);
}
};
export const error = (...args) => {
if (typeof window === 'undefined') return;
const stack = new Error().stack;
if (isLoggingEnabled(stack)) {
console.error(...args);
}
};import { log, warn, error } from '../utils/logger';
function MyComponent() {
log('This will appear only if MyComponent is in ENABLED_PATHS');
return <div>Hello</div>;
}- Just update the
ENABLED_PATHSarray. - You can also make it environment-based, e.g.:
const ENABLED_PATHS = process.env.REACT_APP_DEBUG_PATHS?.split(',') || [];Then in your .env.development.local:
REACT_APP_DEBUG_PATHS=/components/MyComponent,/features/AuthNow you can enable/disable logging without code changes, just by setting the right environment variable and restarting the dev server.
- Add colors to logs (for easier identification).
- Add labels like
[MyComponent]automatically by parsing the stack. - Use
console.groupCollapsed()to organize related logs.
If you want total control, you can override the global console.log too:
const originalLog = console.log;
console.log = (...args) => {
const stack = new Error().stack;
if (stack && stack.includes('/components/MyComponent')) {
originalLog(...args);
}
};Let me know if you want a version that allows regex-based filtering, supports dynamic toggling in browser devtools, or logs with source file info automatically.