Wednesday, November 16, 2011

loggin'

Yesterday I mentioned the importance of "log-based debugging". It's crucial to browser-based work, in part because alert()s and stepping through with the debugger mess up the timing of stuff, so they're not as much help for timing-related issues. I also think the act of putting in log statements forces a programmer to challenge their assumptions.

For reasons that are obscure to me, at work we call our main debug function "ccdebug". Its code is like this:

function ccdebug(s) {
  if (typeof console != "undefined" && typeof console.log != "undefined") {
    console.log(s);
  } 
}

Pretty simple! The check for console existing is necessary for preventing errors when the console isn't around...

I've been using that for just under 100% of my log statements... poking around I realize we have equivalents for console.warn() and console.error(). In firebug, the former has a nice yellow highlight, and the latter even includes a stack trace. So to improve my practice, I should probably start differentiating my information and coding messages from messages for more serious problems.

One other function I find useful, with both console.log() and good old alert():

function inspect(thing, indent){
if(indent == undefined || indent == true){
return JSON.stringify(thing, undefined," ");
}
return  JSON.stringify(thing);
}
That's just a great way to see the content of data structures and what not. The indent makes it a lot more readable, so I include it as the default.

No comments:

Post a Comment