DEV Community

Cover image for Enable or Disable console.log Globally in JavaScript
Eddie Goldman
Eddie Goldman

Posted on

Enable or Disable console.log Globally in JavaScript

Enable or Disable console.log Globally in JavaScript

Sometimes, during development or debugging, you need to quickly enable or disable logging globally across your entire JavaScript application. Here's a straightforward approach to achieve this.

Step-by-Step Guide

Step 1: Store the Original console.log

Before we override the console.log function, it's crucial to keep a reference to the original function.

let original_console_log = console.log;
Enter fullscreen mode Exit fullscreen mode

This ensures you can restore the original functionality anytime you want.

Step 2: Create a Control Function

Next, create a function that can toggle logging on and off by replacing console.log.

let logging_enabled = true;

function set_logging(enabled) {
    logging_enabled = enabled;
    console.log = enabled ? original_console_log : function () {};
}
Enter fullscreen mode Exit fullscreen mode

Here's what's happening:

  • When enabled is true, console.log points back to its original behavior.
  • When enabled is false, console.log becomes an empty function, effectively doing nothing.

Step 3: Enable or Disable Logging

Now you can use your set_logging function to control logging:

set_logging(true);  // Enables logging
console.log('Logging is enabled!');  // βœ… Appears in console

set_logging(false); // Disables logging
console.log('Logging is disabled.'); // ❌ Will NOT appear

set_logging(true);  // Enables logging again
console.log('Logging is re-enabled!'); // βœ… Appears in console
Enter fullscreen mode Exit fullscreen mode

Practical Example

Here's a complete usage scenario:

let original_console_log = console.log;
let logging_enabled = true;

function set_logging(enabled) {
    logging_enabled = enabled;
    console.log = enabled ? original_console_log : function () {};
}

set_logging(true);  // Enables logging
console.log('Always works');  // Appears

set_logging(false); // Disables logging
console.log('This will not appear');  // Does NOT appear

set_logging(true);  // Enables logging again
console.log('This will appear');  // Appears
Enter fullscreen mode Exit fullscreen mode

Why use this method?

  • Global control: Quickly enable or disable logs across your entire application.
  • Clean console: Useful to prevent unnecessary clutter when debugging specific parts of your code.

Caution

Overriding console.log globally might have side effects if your application or external libraries depend heavily on logging. Use with caution and primarily for development or debugging scenarios.

Top comments (1)

Collapse
 
lovit_js profile image
Lovit

Super handy tip! πŸ”§ Love the quick toggle for console.logβ€”perfect for decluttering during deep debugging sessions.