dO-BoY

console.log(‘Blues’)

In web development, the first 90% of development time is devoted to all the other browsers, and another 90% of the time is devoted to Internet Explorer. Thanks to Firebug in Firefox and Safari’s excellent developer tools, I’ve given up hideous “alert-debugging” in favor of logging informative messages to the console with console.log('a message'). You can even get a little fancy with printf-style formatted output, e.g., console.log("var i: %s",i).

But then development moves to IE, and I get bitten by the forgotten console.log() left in the code somewhere. Presumably, IE9 will have some kind of console, but we’ll be testing back to IE6 for years, so this is a problem that’s not going away.

I’ve seen a lot of “solutions” that create new jQuery functions–and we’re all using jQuery now anyway, right?–like $.log() and then you’re supposed to stop using console.log() in favor of this new function.

But I’m a stubborn old man, and my arthritic old fingers won’t soon forget the keystrokes, so I find this approach a little unworkable. What I really want is to leave console.log() alone if it’s available, and if not, drop a DIV into the page to send output to. So I used the code from the above link as a point of departure, and worked it into something that does what I want:


jQuery.extend({
log: function(msg) {
$("body").append("<div style=\"width:600px;color:#fff;background-color:#666;\">" + msg + "</div>");
return true;
}
});

// create object and define method if not present
if ( !window.console )
{
window.console = new Object;
window.console.log = $.log;
}

The strategy is, define a jQuery function $.log() (or jQuery.log() if you prefer) and then assign it to console.log() if it doesn’t already exist. The last block is the key: create an object window.console and assign $.log to a method in the object.

Now I can continue leaving console.log() in my code to debug. If window.console exists, $.log() is defined but never used; if window.console does not exist, it is created and passed $.log and uses that.

Now I just have to remember to include a file debug.js which contains this mess, but to me that’s easier than learning a whole new function which also requires the extra code to define it anyway.