jQuery.log(), Logging plugin for jQuery

For the people who works with JavaScript, logging is very important for debugging. Before I start using Firebug plug-in for Firefox I used the alert function. It worked in all browsers, and it's easy to use. But for big application where you are working with kilobytes of JavaScript code, it's not the best option because you have to click on "OK" button whenever see this window. If it is one or two times it's not a problem, but anyway it's annoying.

Firebug has a great number of methods for logging such as console.log, console.debug, console.info, console.warn ... All these methods provide you with logging messages in Firebug console, but with different icons. While console.log is very convenient, not all browsers support it, and you may get an error message because console.log is not defined.

So the best solution is to create a wrapper for JavaScript logging. You can just create a method for this purpose, but I like jQuery and prefer to build plugin for it.

Creating jQuery plug-in for logging. jQuery.log()

jQuery is an excellent library and allows a lot of kinds of stuff, and one of the most important features is creating plug-ins. All plug-in in jQuery have pattern like the following:

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

Inside of plug-in, I check if the browser supports console because if this is an old version of Internet Explorer, the console will be undefined. There are at least two types of checking if the console is defined, the first is check if it inside of a window, and the second, check if it is not undefined, I prefer the 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 there.


Social media


Latest Tweets