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!
Nice, will be using this instead of my own lil snippet while developing jQuery plugins.
Hey, why are you using an internal undocumented object to store data? You can store the log on the $.log function itself!
Anyway, some useful stuff again!
@Balazs, good point, just changed it. 🙂
James,
Great posts lately.
I was using a similar script (with console.log.apply), but saw that Safari and Chrome’s consoles don’t play nicely with it.
This seemed to be an ugly but functional cross browser solution: