java打印完整的堆棧信息,記錄到錯誤日志,看線上錯誤日志能更快的排錯

在實際的項目中,會遇到各種各樣的異常,我們要排錯的時候,借助錯誤的堆棧信息往往能更快的排錯,所以可以把錯誤堆棧信息寫到日志里面去,方便于看線上的錯誤日志,更快的排錯。

1、使用 io 流將堆棧信息打印出來

public static StringgetStackTraceInfo(Exception e){

StringWriter sw =null;

? ? PrintWriter pw =null;

? ? try {

sw =new StringWriter();

? ? ? ? pw =new PrintWriter(sw);

? ? ? ? //將出錯的棧信息輸出到printWriter中

? ? ? ? e.printStackTrace(pw);

? ? ? ? pw.flush();

? ? ? ? sw.flush();

? ? }finally {

if (sw !=null) {

try {

sw.close();

? ? ? ? ? ? }catch (IOException e1) {

e1.printStackTrace();

? ? ? ? ? ? }

}

if (pw !=null) {

pw.close();

? ? ? ? }

}

if(sw!=null){

return? sw.toString();

? ? }else{

return null;

? ? }

}

2、使用 common-lang3 提供的工具類

在 common-lang3 包中提供了 ExceptionUtils 類來幫助讀取堆棧信息

pom 依賴:

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.5</version>

</dependency>

public static String getStackTraceV2(Exception e) {

? ? return org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);

}

看一下源碼咋實現的:

//-----------------------------------------------------------------------

/**

? * <p>Gets the stack trace from a Throwable as a String.</p>

? *

? * <p>The result of this method vary by JDK version as this method

? * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}.

? * On JDK1.3 and earlier, the cause exception will not be shown

? * unless the specified throwable alters printStackTrace.</p>

? *

? * @param throwable? the <code>Throwable</code> to be examined

? * @return the stack trace as generated by the exception's

? *? <code>printStackTrace(PrintWriter)</code> method

? */

public static String getStackTrace(final Throwable throwable) {

? ? final StringWriter sw = new StringWriter();

? ? final PrintWriter pw = new PrintWriter(sw, true);

? ? throwable.printStackTrace(pw);

? ? return sw.getBuffer().toString();

}

和第一種方法一樣,所以很多東西,別人已經造好輪子了,我們可以直接使用,但是我們也要明白其實現原理。

以下是實際項目中的使用,采用第二種方法:

try {

…………………………

…………………………

}

}catch (Exception e) {

log.error("系統定時驗票:Util.invoiceCheck這邊發生異常:{}",org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e));

? ? e.printStackTrace();

}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。