Java如何打印完整的堆棧信息
Java print full StackTrace
我們在編寫一些組件時,使用的日志系統(tǒng)有時并不能打印完整的堆棧信息,比如slf4j,log4j,我們在調(diào)用log.error("found error ...",e)打印異常時,只打印一行異常信息。我們看下slf4j的源碼
/** * Log an exception (throwable) at the ERROR level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void error(String msg, Throwable t);
它在打印exception時,只是打印了堆棧當中的第一行Throwable的信息, 而我們想要的是把整個堆棧都打印出來,這時我們會用下面方式打印堆棧信息。
demo
e.printStackTrace()
堆棧信息定向到日志文件中
這雖然打印了完整的堆棧信息,但它并不會把堆棧信息定向到日志文件中,這時我們就需要利用輸出流把信息重新定到變量中,然后再送入到日志系統(tǒng)中
/**
* 完整的堆棧信息
*
* @param e Exception
* @return Full StackTrace
*/
public static String getStackTrace(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}然后我們這樣調(diào)用就解決了這個問題
log.error("fount error...", getStackTrace(e))以上就是Java如何打印完整的堆棧信息的詳細內(nèi)容,更多關(guān)于Java打印完整堆棧信息的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring Boot 基于注解的 Redis 緩存使用詳解
淺談javaSE 面向?qū)ο?Object類toString)

