Google analytics code

Friday, September 25, 2009

Flex / ActionScript: Debugging

I ran into an issue while working on a project in flex. I was trying to figure out why something wasn't working and had a large amount of trace calls in my code. It was a complete pain to remove them all. This lead me to develop a debug class that I can turn off at a page level or you can turn if off in the class. It's a first draft. I'd like to make it a Singlton so I can turn it off for the whole project at a page level, but that's for later.

package 
{
public class Debug
{
private var _displayDebug:Boolean = false;
private var _incomingClass:String = "";
private var _logArray:Array = [];

//to stop all debugging set this to false
private var _turnOffDebug:Boolean = false;

/**
* Create the debug object 
* @param display
* @param fileName
* 
*/
public function Debug(display:Boolean, fileName:String): void {
_displayDebug = display;
_incomingClass = fileName;
}


/**
* Display a trace message 
* @param msg
* 
*/
public function log(msg:String) : void {
//override anything a debug passes in
if(_turnOffDebug) {
return;
}

if(!_displayDebug) {
return;
}

var logMessage:String = "["+ new Date() +"]" + _incomingClass + ": " + msg; 

trace(logMessage);
_logArray.push(logMessage);
}
}
}


Using the class is simple. First create an instance of the class and tell if wither you want it on and what the name of the script you're calling it from is named.
var debugObj:Debug = new Debug(true, 'main.mxml');


To turn off debugging for the script just set the first parameter to false. To turn it off for the whole project change the class variable _turnOffDebug to true;

Use the log method to display your statement in the debug area of flash or flex.
debugObj.log('debug statement');


This is a what the trace statement should look like.
[Fri Sep 25 15:03:21 GMT-0700 2009]main.mxml: debug statement

If you have any feedback please send me a message.

2 comments:

  1. Making your own debugger is cool and all but maybe the next programmer who would take over your code may have experience using the Flex Logging API

    http://livedocs.adobe.com/flex/3/html/help.html?content=logging_09.html

    -mL
    knowledge.lapasa.net

    ReplyDelete
  2. That's really cool. Looks far more robust than my stuff. I'll have to look into that.

    Sometimes I like creating my own wheel so I have an idea what it takes to make one. Helps me learn.

    ReplyDelete

If you found this page useful, or you have any feedback, please leave a comment.