Cross browser Console augmentation with debug switch

Many times I need to write debug statements in my web application. These statements can be consoles or alerts depending on browser compatibility. Problem is that some browsers support logging, some don’t and others support logging by use of extension. Few differences:

  1. Firefox supports logging using window.console.log after installing Firebug. If firebug is not installed, console statements break the application.
  2. There is no console logging support in Internet Explorer.
  3. Chrome and Safari have native support for logging using window.console.log
  4. Opera supports logging using window.opera.postError.

Besides the differences, whenever I move my code to production I need to remove/comment all debug statements because they might break the application at user’s computer if proper debug statements are not supported by their browsers. I checked all the debug support in major browsers and came up with this script which resolves above issues.

//Call this function after body load
function manageDebug(){
  var debug = false;
  if(window.console) {
    var consoleBackUp = window.console.log;
    window.console.log = function(str) {
      if(debug) {
        consoleBackUp.call(this,str);
      }
    }
  } else {
    var log = window.opera ? window.opera.postError : alert;
    window.console = {};
    window.console.log = function(str) {
      if(debug) {
        log(str);
      }
    }
  }
} //manageDebug ends

manageDebug();
console.log("This works!");

Few advantages:

  • This script will enable you to write debug statements in your code without thinking about their cross browser compatibility. You can use console.log() in any browser.
  • You don’t need to remove them before moving to production. Just disable the debug flag (debug = false) and it takes care. [Make sure that you don't add too many consoles to contribute to size of the file.]

You need to call manageDebug after body load because it needs to check against window.console. Above script has been tested on Firefox, Chrome, Safari, Opera and Internet Explorer. Hope it helps you to decrease your debugging time!

7 thoughts on “Cross browser Console augmentation with debug switch

  1. Does this endure a performance cost? For each log call, the debug flag needs to be checked, what is the impact of this check on performance?

  2. Yes its a performance overhead but almost negligible. You are not expected to write thousands of consoles in your app, which will affect both size and speed of app.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>