发布于 2015-12-20 23:25:26 | 672 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的Java函数式编程,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


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


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务