博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java打印完整的堆栈信息
阅读量:7219 次
发布时间:2019-06-29

本文共 1305 字,大约阅读时间需要 4 分钟。

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))

转载地址:http://gmxym.baihongyu.com/

你可能感兴趣的文章
第十篇、自定义UIBarButtonItem和UIButton block回调
查看>>
复分析学习1
查看>>
Java虚拟机笔记(四):垃圾收集器
查看>>
计算机运行命令全集
查看>>
WebSocket 实战
查看>>
二次排序
查看>>
CSS:如何清除a标签之间的默认留白间距
查看>>
selenium随笔
查看>>
leetcode599
查看>>
String类中“==”和“equals()”的区别
查看>>
leetcode--883
查看>>
the application could not be verified
查看>>
[转]Centos配置国内yum源
查看>>
redis数据类型和应用场景
查看>>
Spring IOC
查看>>
Fragment的onCreateView和onActivityCreate之间的区别(转)
查看>>
AC日记——统计难题 hdu 1251
查看>>
在仿真器中运行时跳过Windows Azure Startup任务
查看>>
android 获取路径目录方法以及判断目录是否存在,创建目录
查看>>
数列问题[HAOI2004模拟]
查看>>