dbug – a console.log (firebug) wrapper
Here’s a chunk of code I use when I’m writing javascript to let me pepper my code with debug statements and not worry about crashing browsers without the firebug functionality (like safary, which has it’s own console.log syntax and will crash if it encounters firebug formated statements):
dbug = {
firebug: false, debug: false, log: function(msg) {},
enable: function() { if(this.firebug) this.debug = true; dbug.log = console.debug; dbug.log('enabling dbug'); },
disable: function(){ if(this.firebug) this.debug = false; dbug.log = function(){}; }
}
if (typeof console != "undefined") { // safari, firebug
if (typeof console.debug != "undefined") { // firebug
dbug.firebug = true; if(window.location.href.indexOf("debug=true")>0) dbug.enable();
}
}
Then you can just put debug statements wherever you like:
dbug.log("the value of x is: %s", x);
Note that this dbug class has an enable and disable function. By default, it’s disabled. You can explicitly change this in your code while you’re working:
dbug.enable();
Finally, once you’re ready to release, you remove that enable() function and push out your code. You can leave your dbug statements in place and then if you hit any page that calls your code and you want to see the debug statements, you just include ?debug=true (or &debug=true if you already have a query string going) and all your debug statements show back up.
Careful though, those things add K to your file size; I typically only leave the debug statements in place that verify that the code is executing properly.
One last thing. If you write all your code this way – object oriented class structures – then you can open up firebug’s js console and poll your objects and see what their status is. So by using debug to see if your code is executing, and polling the values of the objects instantiated, you can figure out a lot about the state of the page.
Follow @clientcide on twitter to get notified of new posts.
To follow me personally on twitter, follow @anutron.
September 20th, 2006 at 4:36 pm
Update: I’ve modified this so that when dbug is disabled, it stores up the messages that have been logged. When you call dbug.enable() in your code or in the console, then it dumps all previously logged messages to the console (and empties the buffer). This means you don’t have to put “?dbug=true” to the url of the page to see the log; you can just enable it at any point and see any messages you might have missed.
November 16th, 2007 at 6:55 am
Very usefull code indeed!
For those who just want not to crash brothers without Firebug, I have make a very little code here.
The good think is you can keep writing console.log in your code.