JavaScript Tip: Save me from console.log errors

It’s bound to happen. You build yourself a sweet webapp with some sweet javascript action and you unleash it to the world only to get angry emails yelling, “IT DOESn’T WoRK! FIX iT okAy?” And it’s the darndest problem because it’s happening to both IE and Firefox users (Chrome and Safari users have been silent) and you can’t replicate it.

And then you spend hours trying to figure out the problem to no avail, leaving you scratching that magnificent head of yours with luscious, flowing hair. You just can’t replicate the problem. But then, after hours and days of staring intently at the screen, you find it. It’s a rogue console.log call that you forgot to comment out. And then you spend the remainder of the week chastising yourself for being stupid.

It happens. (To be fair, it’s not your fault that your users don’t have Firebug or IE Developer Tools installed. Blame it on Mozilla/Microsoft.)

But there’s an easy solution. Just copy the following javascript somewhere in your project, and rest easy:


if(typeof(console) === 'undefined') {
    var console = {}
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

7 thoughts on “JavaScript Tip: Save me from console.log errors

  1. Pingback: Things I Found Interesting Around May 29th | Chris Coyier

  2. Pingback: Joey Nelson: Prevent console.log() errors

  3. Pingback: JavaScript Tip: Bust and Disable console.log « digitalize.ca

  4. Actually the if stmt will always gets executed in IE 8, even when the developer tools window is open, thus resulting in the console object to be always a nul object.

    Instead here is the solution that I used after modifying your code:

    try
    {
    console.log('test');
    }
    catch(err){
    var console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
    }

  5. It’s also possible to replace the entire console with http://jslogger.com . This way you could log the errors remotely and debug them lately. We replaced the entire console with the following code:

    if (jslogger) {
    if(!window.console) window.console = {};
    var methods = ["log", "debug", "warn", "info"];
    for(var i=0;i<methods.length;i++){
    console[methods[i]] = function(){jslogger.log.apply(jslogger, arguments);};
    }
    }

    This way, every call to console.log/info/debug/warn will be tracked in JSLogger

Leave a Reply