Using console logs excessively in production builds

Loading

Eliminating Console Logs in Production Builds

Excessive console logging in production can lead to several problems including:

  • Performance degradation
  • Security risks (exposing sensitive data)
  • Cluttered browser dev tools
  • Increased log storage costs
  • Potential user confusion

Solutions for Clean Production Builds

1. Basic Console Wrapping

// utils/logger.js
const logger = {
  log: (...args) => {
    if (process.env.NODE_ENV !== 'production') {
      console.log(...args);
    }
  },
  warn: (...args) => {
    if (process.env.NODE_ENV !== 'production') {
      console.warn(...args);
    }
  },
  error: (...args) => {
    // Always show errors, even in production
    console.error(...args);
  }
};

export default logger;

2. Babel Plugin for Automatic Removal (Recommended)

Install the transform-remove-console plugin:

npm install babel-plugin-transform-remove-console --save-dev

Then configure in babel.config.js:

module.exports = {
  presets: ['@babel/preset-react'],
  plugins: [
    ['transform-remove-console', { exclude: ['error', 'warn'] }]
  ]
};

3. Webpack Configuration for Create React App

// config-overrides.js
const { override, addWebpackPlugin } = require('customize-cra');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = override(
  (config) => {
    if (process.env.NODE_ENV === 'production') {
      config.optimization.minimizer = [
        new TerserPlugin({
          terserOptions: {
            compress: {
              drop_console: true,
            },
          },
        }),
      ];
    }
    return config;
  }
);

4. Advanced Logger with Log Levels

// utils/advancedLogger.js
const LOG_LEVELS = {
  DEBUG: 0,
  INFO: 1,
  WARN: 2,
  ERROR: 3,
  NONE: 4
};

const currentLevel = process.env.NODE_ENV === 'production' 
  ? LOG_LEVELS.ERROR 
  : LOG_LEVELS.DEBUG;

export default {
  debug: (...args) => currentLevel <= LOG_LEVELS.DEBUG && console.debug(...args),
  info: (...args) => currentLevel <= LOG_LEVELS.INFO && console.info(...args),
  warn: (...args) => currentLevel <= LOG_LEVELS.WARN && console.warn(...args),
  error: (...args) => currentLevel <= LOG_LEVELS.ERROR && console.error(...args),
  // Add methods for remote logging if needed
  remoteError: (error) => {
    console.error(error);
    // Send to error tracking service
  }
};

Best Practices

  1. Use a logging utility instead of direct console calls
  2. Keep error logging in production (but sanitize sensitive data)
  3. Implement log levels for better control
  4. Consider remote logging for critical errors (Sentry, LogRocket)
  5. Document logging standards for your team

Migration Strategy

  1. Replace all console.* calls with your logger utility
  2. Set up the Babel plugin or Webpack configuration
  3. Verify production builds don’t include development logs
  4. Implement code reviews to prevent new console.* additions

Production-Only Considerations

  1. Error tracking services:
   logger.error = (error) => {
     console.error(error);
     if (window.Sentry) {
       Sentry.captureException(error);
     }
   };
  1. Performance monitoring:
   logger.performance = (message) => {
     if (process.env.NODE_ENV === 'production' && window.analytics) {
       analytics.timing(message);
     }
   };
  1. User-facing errors:
   logger.userError = (message) => {
     logger.error(message);
     showUserAlert('Something went wrong'); // Custom UI component
   };

Leave a Reply

Your email address will not be published. Required fields are marked *