JavaScript Tip: Bust and Disable console.log

Here’s a quick and dirty follow-up to my original Save me from console.log errors. The main improvement to this version is that it includes a way to disable console.log (and related functions), for example, in production environments.

While console.log is awesome, you really don’t want your dirty inner workings littering up the Console (or visible to the user — though, you could make an argument that this is a great way to debug errors in live environments) once your app is deployed.

Note: Firebug can get unhappy sometimes if you try to mess with its console object. But, in theory, this approach should work.


var DEBUG_MODE = true; // Set this value to false for production

if(typeof(console) === 'undefined') {
    console = {}
}

if(!DEBUG_MODE || typeof(console.log) === 'undefined') {
    // FYI: Firebug might get cranky...
    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() {};
}

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