Thursday, November 13, 2008

Getting java runtime stack trace

In most of the time finding java runtime stack trace is useful in debugging. The common practice is to run the application in debug mode and find the stack trace.
Here is a way I found to print the stack trace within the java code it self without running in debug mode. I found this in JavaUtils class of the Axis2 kernel.

public static String callStackToString() {
return stackToString(new RuntimeException());
}

public static String stackToString(Throwable e) {
java.io.StringWriter sw = new java.io.StringWriter();
java.io.BufferedWriter bw = new java.io.BufferedWriter(sw);
java.io.PrintWriter pw = new java.io.PrintWriter(bw);
e.printStackTrace(pw);
pw.close();
String text = sw.getBuffer().toString();
// Jump past the throwable
text = text.substring(text.indexOf("at"));
text = replace(text, "at ", "DEBUG_FRAME = ");
return text;
}

No comments: