Mik*_*eck 76
还有一种Throwable.printStackTrace()的替代形式,它将打印流作为参数.http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
例如
catch(Exception e) {
e.printStackTrace(System.out);
}
Run Code Online (Sandbox Code Playgroud)
这会将堆栈跟踪打印到std out而不是std错误.
Mau*_*res 73
不是很漂亮,但仍然是一个解决方案:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
Run Code Online (Sandbox Code Playgroud)
Boz*_*zho 56
Throwable.printStackTrace(..)
可以采取PrintWriter
或PrintStream
参数:
} catch (Exception ex) {
ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}
Run Code Online (Sandbox Code Playgroud)
也就是说,考虑使用像SLF4J这样的记录器接口和LOGBack或log4j等日志记录实现.
Apache commons 提供了将堆栈跟踪从 throwable 转换为字符串的实用程序。
用法:
ExceptionUtils.getStackTrace(e)
Run Code Online (Sandbox Code Playgroud)
有关完整文档,请参阅 https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html
小智 7
我创建了一个有助于获取 stackTrace 的方法:
private static String getStackTrace(Exception ex) {
StringBuffer sb = new StringBuffer(500);
StackTraceElement[] st = ex.getStackTrace();
sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
for (int i = 0; i < st.length; i++) {
sb.append("\t at " + st[i].toString() + "\n");
}
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)