Figured some people might like this in case they miss it for some reason, they can log it to a file with this string...
Code:
public static String generateStack(Throwable throwable) {
try {
StackTraceElement[] element = throwable.getStackTrace();
StringBuilder builder = new StringBuilder();
builder.append(throwable+"\n");
for(StackTraceElement e : element) {
builder.append("\tat "+e+"\n");
}
throwable.printStackTrace();
Throwable cause = throwable.getCause();
if(cause != null)
addCause(cause, element, builder);
return builder.toString();
} catch(Exception e) {
e.printStackTrace();
}
return "Could not generate stacktrace.";
}
public static void addCause(Throwable cause, StackTraceElement[] causedTrace, StringBuilder builder) {
StackTraceElement[] trace = cause.getStackTrace();
int m = trace.length-1, n = causedTrace.length-1;
while (m >= 0 && n >=0 && trace[m].equals(causedTrace[n])) {
m--; n--;
}
int framesInCommon = trace.length - 1 - m;
builder.append("Caused by: " + cause + "\n");
for (int i=0; i <= m; i++)
builder.append("\tat " + trace[i]+"\n");
if (framesInCommon != 0)
builder.append("\t... " + framesInCommon + " more"+"\n");
// Recurse if we have a cause
Throwable ourCause = cause.getCause();
if (ourCause != null)
addCause(ourCause, trace, builder);
}
Taken from the Throwable.printStackTrace() method, which prints it to System.err, and changed to a stringbuilder.