【问题标题】:How to store printStackTrace into a string [duplicate]如何将 printStackTrace 存储到字符串中[重复]
【发布时间】:2011-06-16 07:15:15
【问题描述】:

如何获取e.printStackTrace() 并将其存储到String 变量中? 我想稍后在我的程序中使用e.printStackTrace() 生成的字符串。

我还是 Java 新手,所以我对 StringWriter 不太熟悉,我认为 将是解决方案。或者,如果您有任何其他想法,请告诉我。谢谢

【问题讨论】:

  • 实际上不是同一个问题:另一个问题实际上指定他们只是想将Throwable.getStackTrace() 的结果转换为字符串。这可能包含比Throwable.printStackTrace 显示的信息少得多。

标签: java stack-trace


【解决方案1】:

类似

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

应该是你需要的。

相关文档:

【讨论】:

  • @Zach L - 感谢您的回答。它对我有用,可以打印堆栈跟踪以及个性化(自定义)错误消息。再次感谢您的帮助。
  • 这也打印了引发异常的嵌套原因,这正是我所需要的。谢谢!
  • 在使用后关闭PrintWriter如何释放资源?阅读我发现 StringWriter 不需要的文档。
【解决方案2】:

Guava 使用Throwables.getStackTraceAsString(Throwable) 让这一切变得简单:

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

在内部,这符合@Zach L 的建议。

【讨论】:

    【解决方案3】:

    您可以使用来自 Apache Commons 3 类 org.apache.commons.lang3.exception.ExceptionUtilsExceptionUtils.getStackTrace(Throwable t);

    http://commons.apache.org/proper/commons-lang/

    ExceptionUtils.getStackTrace(Throwable t)

    代码示例:

    try {
    
      // your code here
    
    } catch(Exception e) {
      String s = ExceptionUtils.getStackTrace(e);
    }
    

    【讨论】:

      【解决方案4】:

      您必须使用getStackTrace () 方法而不是printStackTrace()。这是good example

      import java.io.*;
      
      /**
      * Simple utilities to return the stack trace of an
      * exception as a String.
      */
      public final class StackTraceUtil {
      
        public static String getStackTrace(Throwable aThrowable) {
          final Writer result = new StringWriter();
          final PrintWriter printWriter = new PrintWriter(result);
          aThrowable.printStackTrace(printWriter);
          return result.toString();
        }
      
        /**
        * Defines a custom format for the stack trace as String.
        */
        public static String getCustomStackTrace(Throwable aThrowable) {
          //add the class name and any message passed to constructor
          final StringBuilder result = new StringBuilder( "BOO-BOO: " );
          result.append(aThrowable.toString());
          final String NEW_LINE = System.getProperty("line.separator");
          result.append(NEW_LINE);
      
          //add each element of the stack trace
          for (StackTraceElement element : aThrowable.getStackTrace() ){
            result.append( element );
            result.append( NEW_LINE );
          }
          return result.toString();
        }
      
        /** Demonstrate output.  */
        public static void main (String... aArguments){
          final Throwable throwable = new IllegalArgumentException("Blah");
          System.out.println( getStackTrace(throwable) );
          System.out.println( getCustomStackTrace(throwable) );
        }
      } 
      

      【讨论】:

      【解决方案5】:

      与 Guava 类似,Apache Commons Lang 在org.apache.commons.lang.exception 中有ExceptionUtils.getFullStackTraceFrom a prior answer 在 StackOverflow 上。

      【讨论】:

        【解决方案6】:
        StackTraceElement[] stack = new Exception().getStackTrace();
        String theTrace = "";
        for(StackTraceElement line : stack)
        {
           theTrace += line.toString();
        }
        

        【讨论】:

          【解决方案7】:

          使用 apache commons-lang3 库

          import org.apache.commons.lang3.exception.ExceptionUtils;
          
          //...
          
          String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
          logger.error(StringUtils.join(ss, System.lineSeparator()));
          

          【讨论】:

          • logger.error(StringUtils.join(ss, System.lineSeparator()));
          【解决方案8】:
          call:  getStackTraceAsString(sqlEx)
          
          public String getStackTraceAsString(Exception exc)  
          {  
          String stackTrace = "*** Error in getStackTraceAsString()";
          
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          PrintStream ps = new PrintStream( baos );
          exc.printStackTrace(ps);
          try {
              stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
              } 
          catch( UnsupportedEncodingException ex )
              {
              Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
              }
          ps.close();
          try {
              baos.close();
              } 
          catch( IOException ex )
              {
              Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
              }
          return stackTrace;
          }
          

          【讨论】:

          • 将 PrintWriter 与 StringWriter 一起使用似乎更简单。
          • 关闭PrintWriter 关闭ByteArrayOutputStream
          猜你喜欢
          • 2020-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-07
          • 1970-01-01
          • 1970-01-01
          • 2014-05-06
          • 2021-08-28
          相关资源
          最近更新 更多