Runtime Stack Information for Logging and Debugging

by

Or, “Hack Your Stack for Fun and Profit!” Yes, this is really and truly a hack, my friends, but, like many hacks, you might find it very useful. Using the Stack class I provide, you can get all sorts of information about the code being run right now: the package, class name, method, filename, and even the line number. You can also grab an Array version of a stack trace and follow it up. Sweet!

So check out this egregious hack. First, you grab the stack trace by throwing and catching a dummy Error and copping its stack trace as a string. Note, that this technique only works (and is only useful) in the Debug Player.

public static function getRawStackTrace():String
{
	var stackTrace:String;
	try
	{
		throw new Error();
	} catch (error:Error) {
		stackTrace = error.getStackTrace();
	}
	return stackTrace;
}

Then you slice it up into lines, and hack those lines into their constituent parts by some crazy regular expressions. That’s pretty much it.

public static function getPartsFromStackTraceEntry(stackEntry:String):Object
{
	return stackEntry.match(/(?P<package>[\w\d\.]+)::(?P<classname>[\w\d\.\:]*?)(?P<isStatic>\$?)\/((?P<scope>[\w\d\.\:]+)::)?(?P<method>[\w\d]+\(\))(\[(?P<filename>[\w\d\\\/\.]+):(?P<line>\d+)\])?/);
}

Fun, right? The properties in the returned Object are:

  • package
  • classname
  • isStatic
  • scope
  • method
  • filename
  • line

You can clean this up into package.classname::method with getSimplifiedStackTraceEntry().

So that’s it, it’s just some regular expressions, but with this hack you can pull out all kinds of juicy information about the context your code is running in. It can be useful for your own debugging, logging, and error reporting.

filecom.yourmajesty.debug.Stack View Source | Download (.as, 2k)

  • gabriel

    hey roger, this is nice!

    a thing to note is that in order to get the file name and line on your stack, you also have to compile with -compile.verbose-stacktraces=true flag. If not, the regex might even fail on static methods (it chokes somewhere, I haven’t seen exactly where).

    another thing, in order to catch the file name (and line number, cause the regex passed right through) in my work’s windorz, i had to toss in a : in the filename character class in the regexp. and, although I try not to have spaces in my paths, i guess a space character would also be necessary if you have your project in a path with those in it.