Mar 12
Debug utility
At last, my first tech post. : )
Here’s a way to ease the debugging into flex. I’ve created a simple class which takes advantage of the getStackTrace() method of the Error class and traces the calling function name before any debug message.
package com.ionutgrosu.logging
{
import mx.utils.ObjectUtil;
/**
* @author Ionut Grosu ( http://www.flexwizz.com )
* Simple Debug Util Class
*/
public final class Logger
{
/**
* enable logging
*/
public static var isDebug : Boolean = true;
/**
* Traces a message
* @param str
* @param introspect Set this to true if you want the 1st param to be introspected
*/
public static function log(str : * = '', introspect : Boolean = false):void
{
if(!isDebug) return;
if(introspect) str = ObjectUtil.toString(str);
trace(getCallingFunction(new Error())+ str);
}
/**
* @private
*/
private static function getCallingFunction(err:Error):String
{
return (err.getStackTrace().split("at ")[1].split("()")[0]+'()').replace('/',".") + " ";
}
}
}
You simply use it like Logger.log(”message”) and check the output. Should look similar to appName.componentId.blabla.functionName() “message”.
Of course, you can step in deeper and redirect the output to a custom log target, filter messages and so on. But I’ll come back on this with a more compressive code built on top of logging framework which needs a little cleanup.
Note that the getStackTrace() method is only available in the debug version of flash player so you should disable the logger class when exporting a release version. A single call to getStackTrace() will usually crash the application with no errors. So make sure that you set isDebug to false before any log() calls when releasing.
Cheers.


June 25th, 2009 at 8:20 am
Waw , Great work i have been trying to do this since 2 , 3 days. Now Remaining thing is only the Line Number which i will defiantly Parse through the String. If You have a tried and Best Sample for Returning line number also ,will Appreciate it.
But Great work.
Thanks
June 25th, 2009 at 10:37 am
This has actually turned into an more compressive logging system that is used internally (I will post details over that a little later. Didn’t have much time for blogging lately).
What you need can be done in many ways. One easy way is to use a regular expression to match that. The regular expression looks like this /:\d+]/ . When applied to a single line from the error stack will match this :lineNumber]
So for example ( if err is Error ) this will output the line number:
var lineNumber : uint;
var loc : String = err.getStackTrace().split(”at “)[1].split(”()”)[1];
var match : Array = loc.match(/:\d+]/gi);
if(match && match.length > 0)
{
lineNumber = parseInt(String(match[0]).substr(1,match[0].length-1));
trace( “lineNumber:”+ lineNumber);
}
June 25th, 2009 at 1:58 pm
Thanks a lot, ITs Working for me