Skip to content

Instantly share code, notes, and snippets.

@induratized
Last active October 20, 2025 05:15
Show Gist options
  • Select an option

  • Save induratized/ee6cb311cbeef48f0b9f9f84b5ad77dd to your computer and use it in GitHub Desktop.

Select an option

Save induratized/ee6cb311cbeef48f0b9f9f84b5ad77dd to your computer and use it in GitHub Desktop.
Custom javascript logger

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.


βœ… Quick, Flexible Solution: Custom logger.js Wrapper

Step 1: Create logger.js

// 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);
  }
};

Step 2: Use the Logger in Your Code

import { log, warn, error } from '../utils/logger';

function MyComponent() {
  log('This will appear only if MyComponent is in ENABLED_PATHS');
  return <div>Hello</div>;
}

πŸ”„ How to Enable/Disable Quickly

  • Just update the ENABLED_PATHS array.
  • 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/Auth

Now you can enable/disable logging without code changes, just by setting the right environment variable and restarting the dev server.


Optional Enhancements

  1. Add colors to logs (for easier identification).
  2. Add labels like [MyComponent] automatically by parsing the stack.
  3. Use console.groupCollapsed() to organize related logs.

Want to Silence All Logs Except Yours?

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);
  }
};

⚠️ Use this only in development and with caution.


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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment