Looking up the calling function

Ralf Bokelberk had a nice idea about how to get dynamically to the function name of the calling function. This may sound a little bit wired, but if you do debugging it is nice to do something like Logger.add( 'log this infomration', ... ); and then have the output with the calling function (and maybe line number).
For instance something like com.test.package::Class/function(): log this information.

Now the solution Ralf had is throwing an error and get to the whole stuff by using the stack trace. This works pretty well. In debug mode you can also send line-numbers and file information to your log output which is very nice.

[as]var stackTrace: String;

try { throw new Error(); }
catch ( e: Error ) { stackTrace = e.getStackTrace(); }

var lines: Array = stackTrace.split( “\n” );
var isDebug: Boolean = ( lines[ int( 1 ) ] as String ).indexOf( ‘[' ) != int( -1 );

var path: String;
var line: int = -1;

if ( isDebug )
{
var regex: RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches: Array = regex.exec( lines[ int( 2 ) ] );

path = matches[ int( 1 ) ];

//file:line = matches[2]
line = matches[ int( 2 ) ].split( ‘:’ )[ int( 2 ) ];//windows == 2 because of drive:\
}
else
{
path = ( lines[ int( 2 ) ] as String ).substring( 4 );
}

msg = path + ( line != -1 ? ‘[' + line.toString() + ']‘ : ” ) + ‘: ‘ + msg;[/as]

Related Posts

1 Response to “Looking up the calling function”


  1. 1 Nate Chatellier

    What a brilliant idea! I added the to my customer logger class and it has been so helpful already. Thanks!

Leave a Reply






Close
E-mail It