欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java如何打印完整的堆棧信息

 更新時(shí)間:2023年05月17日 09:51:25   作者:wangjuntytl  
這篇文章主要為大家介紹了Java如何打印完整的堆棧信息示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

Java print full StackTrace

我們?cè)诰帉懸恍┙M件時(shí),使用的日志系統(tǒng)有時(shí)并不能打印完整的堆棧信息,比如slf4j,log4j,我們?cè)谡{(diào)用log.error("found error ...",e)打印異常時(shí),只打印一行異常信息。我們看下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時(shí),只是打印了堆棧當(dāng)中的第一行Throwable的信息, 而我們想要的是把整個(gè)堆棧都打印出來,這時(shí)我們會(huì)用下面方式打印堆棧信息。

demo

e.printStackTrace()

堆棧信息定向到日志文件中

這雖然打印了完整的堆棧信息,但它并不會(huì)把堆棧信息定向到日志文件中,這時(shí)我們就需要利用輸出流把信息重新定到變量中,然后再送入到日志系統(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)用就解決了這個(gè)問題

log.error("fount error...", getStackTrace(e))

以上就是Java如何打印完整的堆棧信息的詳細(xì)內(nèi)容,更多關(guān)于Java打印完整堆棧信息的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論