2011-01-27 25 views
168

¿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.Cómo almacenar printStackTrace en una cadena

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

Respuesta

356

Algo a lo largo de las líneas de

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

debería ser lo que necesita.

documentación pertinente:

+0

@Zach L Apache Commons-lang3 - Gracias por su respuesta. funcionó para mí imprimir el seguimiento de la pila junto con un mensaje de error personalizado (personalizado). De nuevo, gracias por tu ayuda. –

+2

Esto imprime las causas anidadas de la excepción lanzada también, que es justo lo que necesitaba. ¡Gracias! –

+3

¿qué hay de cerrar 'PrintWriter' después del uso para liberar recursos? Al leer los documentos, descubrí que no es necesario para StringWriter. – jelies

4
StackTraceElement[] stack = new Exception().getStackTrace(); 
String theTrace = ""; 
for(StackTraceElement line : stack) 
{ 
    theTrace += line.toString(); 
} 
11

Usted tiene que usar getStackTrace() método en lugar de printStackTrace(). Aquí está una 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)); 
    } 
} 
10

En la línea de Guava, Apache Commons Lang tiene ExceptionUtils.getFullStackTrace en org.apache.commons.lang.exception. From a prior answer en StackOverflow.

0
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

El uso de un PrintWriter con un StringWriter parece ser más sencillo. – gouessej

+0

Al cerrar el 'PrintWriter' se cierra' ByteArrayOutputStream'. – EJP

1

Uso del lib

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

//... 

String[] ss = ExceptionUtils.getRootCauseStackTrace(e); 
logger.error(StringUtils.join(ss, System.lineSeparator())); 
+1

'logger.error (StringUtils.join (ss, System.lineSeparator()));' – pisaruk

Cuestiones relacionadas