I always found myself forgetting to remove the numerous console.log calls within my scripts after debugging so I created a little jQuery plugin to deal with it. If the user has no console it won’t fail, so there’s no need to worry anymore!

The Code:

$.log = $.fn.log = function(o) {
 
    window.console && console.log ?
        console.log.apply(console, !!arguments.length ? arguments : [this])
    : opera && opera.postError
        && opera.postError(o || this);
 
    $.log.cache = $.log.cache || [];
    $.log.cache[$.log.cache.length] = arguments.length > 1 ? arguments : o || this;
    return $.log.cache.length-1;
 
}

It’s a pretty concise plugin, it will check for the presence of a console or the equivalent utility in Opera and if present will post a log/error, otherwise it will exit smoothly… It will also save a cache of the log accessible as a property: ($.log.cache).

Usage:

// Log: Method #1
$.log('Log this message.');
 
// Log: Method #2
$('a').log(); // Logs all anchors
 
// Reading the cache:
// The log cache is an array, you can access it like this:
var logArray = $.log.cache;
 
// Or, to access a specific log:
var logIndex = $('div').log(); // Returns index of log
alert( $.log.cache[logIndex] );

Non-jQuery:

If you’re not using jQuery then this simple log function does the same:

window['log'] = function(o) {
 
    window.console && console.log ?
        console.log.apply(console, !!arguments.length ? arguments : [this])
    : opera && opera.postError
        && opera.postError(o || this);
 
    window.log.cache = window.log.cache || [];
    window.log.cache[window.log.cache.length] = arguments.length > 1 ? arguments : o || this;
    return window.log.cache.length-1;
 
}
 
// Log something:
log('Blah blah blah');
 
// Retrieve cache:
alert(log.cache);

I hope you find this useful!

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!