How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?
I found Thread.dumpStack()
but it is not what I want -
You can use Thread.currentThread().getStackTrace()
.
That returns an array of StackTraceElements that represent the current stack trace of a program.
You can use Apache's commons for that:
String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
I suggest that
Thread.dumpStack()
is an easier way and has the advantage of not actually constructing an exception or throwable when there may not be a problem at all, and is considerably more to the point.
try {
}
catch(Exception e) {
StackTraceElement[] traceElements = e.getStackTrace();
//...
}
or
Thread.currentThread().getStackTrace()
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().
loop through StackTraceElement and get your desired result.
for (StackTraceElement ste : stackTraceElements )
{
//do your stuff here...
}
I used answers from above and added formatting
public final class DebugUtil {
private static final String SEPARATOR = "\n";
private DebugUtil() {
}
public static String formatStackTrace(StackTraceElement[] stackTrace) {
StringBuilder buffer = new StringBuilder();
for (StackTraceElement element : stackTrace) {
buffer.append(element).append(SEPARATOR);
}
return buffer.toString();
}
public static String formatCurrentStacktrace() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
return formatStackTrace(stackTrace);
}
}