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() {};
}
Things I Found Interesting Around May 29th | Chris Coyier 8:44 am on May 30, 2010 Permalink |
[...] Javascript Tip: Save me from console.log errors [...]
Joey Nelson: Prevent console.log() errors 2:20 pm on July 14, 2010 Permalink |
[...] Really smart [...]
JavaScript Tip: Bust and Disable console.log « digitalize.ca 1:02 pm on February 16, 2011 Permalink |
[...] 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 [...]
Chris Marisic 3:38 pm on March 8, 2011 Permalink |
Nice article, I just came across this bug affecting orbit jquery slider and posted your article to them https://github.com/zurb/orbit/issues/6 :)
Jatinder Assi 3:52 pm on September 27, 2011 Permalink |
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() {};
}
Mohammad Jangda 12:19 am on October 3, 2011 Permalink |
Thanks for the tip. That’s definitely good to know!