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的信息, 而咱们想要的是把整个堆栈都打印出来,这时咱们会用下面方式打印堆栈信息。code

e.printStackTrace()

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

/**
     * 完整的堆栈信息
     *
     * @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))
相关文章
相关标签/搜索