|
For the people who working with JavaScript, logging is very important for debugging. Before I start using Firebug plug-in for Firefox I used alert function. It works in all browsers, and it's quickly to use.
But for big application where you working with kilobytes of JavaScript code it's not the best option, because you have to click on "OK" button every time when see this window, and if it one or two times it's not a problem, but anyway it's annoying.
But Firebug has a great number of methods for logging it's
console.log
console.debug
console.info
console.warn
......
All this methods provide you with logging messages in Firebug console, but with different icons. But anyway in my opinion the most popular is console.log
If you want to test your application in browsers different from Firefox, your will have error message, because console.log is not define, so the best solution is create wrapper for JavaScript logging.
You can just create a method for this purpose, but I like jQuery and prefer to create plugin for jQuery.
Creating jQuery plug-in for logging. jQuery.log()
jQuery it's a great library and allow a lot of stuffs, and one of the most important feature is creating plug-in.
All plug-in in jQuery have pattern it's :
(function($) {
// your plug-in code here
})(jQuery);
This patterns allow you to user $ for accessing jQuery inside of plug-in and help to hide some internal methods and properties because of closure.
I want to access my logging plug-in this way
$.log('my message');
The code for jQuery log plug-in is below
(function($) {
$.log =
{
log: function(message) {
//if('console' in window && 'log' in window.console)
if (typeof window.console != 'undefined' && typeof window.console.log != 'undefined') {
console.log(message);
}
else {
// do nothing
//alert('console is not supported: ' + message);
}
},
info : function(message) {
// todo
}
}
})(jQuery);
Inside of plug-in I check if the browser supports console, because if this is old version of Internet explorer, or if in Firefox you close Firebug plug-in console will be undefined. There is at least two types of checking if console is defined, the first is check if it inside of window, and the second, check if it is not undefined, I prefer second.
I put just console.log() method inside of my logging method, but if you need to support more browsers, for example Opera... you can add more code in this method.
And it's all that you need. Now you can save this file as jquery.log.js and attach it to your project.
Happy JavaScript programming :)
|