Java打印完整的堆栈信息

发布时间:2019-11-18 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Java打印完整的堆栈信息脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Java PRint full StackTrace

我们在编写一些组件时,使用的日志系统有时并不能打印完整的堆栈信息,比如slf4j,LOG4j,我们在调用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的信息, 而我们想要的是把整个堆栈都打印出来,这时我们会用下面方式打印堆栈信息。

 e.printStackTrace()

这虽然打印了完整的堆栈信息,但它并不会把堆栈信息定向到日志文件中,这时我们就需要利用利用输出流把信息重新定到变量中,然后再送入到日志系统中

/**      * 完整的堆栈信息      *      * @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();     }

然后我们这样调用就解决了这个问题

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

脚本宝典总结

以上是脚本宝典为你收集整理的Java打印完整的堆栈信息全部内容,希望文章能够帮你解决Java打印完整的堆栈信息所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。