Cómo almacenar printStackTrace en una cadena [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Cómo puedo obtener el e.printStackTrace() y almacenarlo en una variable String? Quiero usar la cadena generada por e.printStackTrace() más adelante en mi programa.

Todavía soy nuevo en Java, así que no estoy muy familiarizado con StringWriter que creo será la solución. O si tienes alguna otra idea por favor hágamelo saber. Gracias

Author: BalusC, 2011-01-27

8 answers

Algo parecido a

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

Debería ser lo que necesitas.

Documentación pertinente:

 388
Author: Zach L,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-19 07:43:15

Guayaba hace esto fácil con Lanzables.getStackTraceAsString (Lanzable):

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

Internamente, esto hace lo que @Zach L sugiere.

 63
Author: ColinD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-11 05:40:17

Tienes que usar el método getStackTrace () en lugar de printStackTrace(). He aquí un buen ejemplo :

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) );
  }
} 
 11
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-27 03:59:40

A lo largo de las líneas de Guava, Apache Commons Lang tiene ExceptionUtils.getFullStackTrace en org.apache.commons.lang.exception. De una respuesta anterior en StackOverflow.

 11
Author: Mihai Danila,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:31

Puede usar el ExceptionUtils.getStackTrace(Throwable t); de la clase org.apache.commons.lang3.exception.ExceptionUtils de Apache Commons 3.

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

ExceptionUtils.getStackTrace (t lanzable)

Ejemplo de código:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}
 10
Author: thiagoh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-07 23:24:10
StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}
 4
Author: Jonathon Faust,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-27 03:59:01

Utilice apache commons-lang3 lib

import org.apache.commons.lang3.exception.ExceptionUtils;

//...

String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));
 1
Author: Eric Wang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-17 16:32:11
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;
}
 0
Author: Stan Towianski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-09 16:18:43