11 August 2005

Neat Trick #1

How to log a message identifying the location in code

Consider this code:

public class Debug
{
public static void debug(String message)
{
StackTraceElement ste =
new Throwable().getStackTrace()[1]; // <==
System.out.println("[" + ste.getFileName()
+ ":"
+ ste.getLineNumber()
+ "] "
+ message);
}
}


Now we can call this from other code:

public class LoggerDemo
{
public static void main(String[] args)
{
Debug.debug("Test Message");
}
}


The output will look something like this - note that we get the source file name and line number where the call was made:

[LoggerDemo.java:16] Test Message


This can be an extremely useful trick. The secret to how this works is all in the line marked with the "<==" marker comment.

Whenever a Throwable object is created (or an Exception, which is a subclass of Throwable), the JVM creates a stack trace in the form of an array of StackTraceElement objects. (Note that you can create a Throwable object using new just like any other class, and just because it's Throwable doesn't mean that it must be thrown.) The getStackTrace() method returns the stack trace array.

The elements of the array are ordered starting at the point in the code where the Throwable was created, so element 0 would contain details about the line containing the new Throwable() call. Element 1 is the one we want because it tells us about where the debug() method was called from.

As you can see the StackTraceElement contains information about the source file and line number. It also contains the class and method name, so our debug() method could report that too if it was useful.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home