Java打印完整的堆栈信息
2015-10-13 15:53
525 查看
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多线程编程总结
- Spket在eclipse中使用,ExtJS的好帮手
- Java中部分关键字
- struts2学习04——数据封装核心机制
- Java 异常笔试题
- java的HashSet的介绍
- JAVA从入门到精通读书笔记 第四章
- java多线程学习笔记(三) ——多线程实例火车票问题+同步synchronized初接触
- java7中G1垃圾收集器使用和流程总结
- 【第五节】Java代码实现队列----【链表的存储形式】
- Eclipse闪退/打不开/无法启动/一闪而过
- Java基础知识强化之多线程笔记04:并行和并发 区别
- Hibernate 学习入门2
- 字典树java版本
- 停止Eclipse LogCat的自动滚动
- java八大排序算法实现
- java.lang.OutOfMemoryError: PermGen space
- 运行Java的基础
- 通过java api 读取sql 中数据(查询)
- java中接口的定义与实现