Obtener seguimiento de pila actual en Java
Cómo obtengo el seguimiento de pila actual en Java, como cómo en . NET puede hacer Environment.StackTrace
?
POR cierto, Thread.dumpStack()
no es lo que quiero - quiero recuperar el stack trace, no imprimirlo.
22 answers
Puede usar Thread.currentThread().getStackTrace()
.
Que devuelve una matriz de StackTraceElement
s que representan la traza de pila actual de un programa.
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
2014-08-02 16:22:17
Thread.currentThread().getStackTrace();
Está bien si no te importa cuál es el primer elemento de la pila.
new Throwable().getStackTrace();
Tendrá una posición definida para su método actual, si eso importa.
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
2009-07-01 13:29:12
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
System.out.println(ste);
}
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
2012-10-04 06:46:24
Thread.currentThread().getStackTrace();
Está disponible desde JDK1.5.
Para una versión anterior, puede redirigir exception.printStackTrace()
a un StringWriter()
:
StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();
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
2010-04-20 15:32:45
Puedes usar Apache commons para eso:
String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
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-04-03 19:43:43
En Android una forma mucho más fácil es usar esto:
import android.util.Log;
String stackTrace = Log.getStackTraceString(exception);
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
2015-10-26 22:25:07
Para obtener el seguimiento de la pila de todos los subprocesos, puede usar la utilidad jstack, JConsole o enviar una señal kill-quit (en un sistema operativo Posix).
Sin embargo, si desea hacer esto programáticamente, puede intentar usar ThreadMXBean:
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);
for (ThreadInfo info : infos) {
StackTraceElement[] elems = info.getStackTrace();
// Print out elements, etc.
}
Como se mencionó, si solo desea el seguimiento de la pila del hilo actual es mucho más fácil - Solo use Thread.currentThread().getStackTrace()
;
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-05-20 14:43:45
Otra solución (solo 35 31 personajes):
new Exception().printStackTrace();
new Error().printStackTrace();
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-03-18 06:57:28
Tonto de mí, es Thread.currentThread().getStackTrace();
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
2009-07-01 13:31:33
Tony, como comentario a la respuesta aceptada, ha dado lo que parece ser la mejor respuesta que realmente responde la pregunta de la OP :
Arrays.toString(Thread.currentThread().getStackTrace());
... el OP lo hizo NO pregunte cómo obtener un String
del seguimiento de pila de un Exception
. Y aunque soy un gran fan de Apache Commons, cuando hay algo tan simple como lo anterior no hay razón lógica para usar una biblioteca externa.
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-06-07 20:02:05
Para encadenar con guayaba:
Throwables.getStackTraceAsString(new Throwable())
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
2014-02-24 12:45:26
Sugiero que
Thread.dumpStack()
Es una manera más fácil y tiene la ventaja de no construir realmente una excepción o lanzable cuando puede no haber un problema en absoluto, y es considerablemente más al punto.
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-07-18 01:55:40
Tengo un método de utilidad que devuelve una cadena con el stacktrace:
static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}
Y simplemente logit like...
...
catch (FileNotFoundException e) {
logger.config(getStackTrace(e));
}
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
2012-05-06 23:54:10
En Java 9 hay una nueva forma:
public static void showTrace() {
List<StackFrame> frames =
StackWalker.getInstance( Option.RETAIN_CLASS_REFERENCE )
.walk( stream -> stream.collect( Collectors.toList() ) );
for ( StackFrame stackFrame : frames )
System.out.println( stackFrame );
}
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-28 20:47:44
try {
}
catch(Exception e) {
StackTraceElement[] traceElements = e.getStackTrace();
//...
}
O
Thread.currentThread().getStackTrace()
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
2009-07-01 13:19:06
Tal vez podrías probar esto:
catch(Exception e)
{
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
e.printStackTrace(pw);
String errorDetail = writer.toString();
}
La cadena 'errorDetail' contiene el stacktrace.
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
2015-04-20 15:11:59
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
El último elemento de la matriz representa la parte inferior de la pila, que es la invocación de método menos reciente en la secuencia.
A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().
Haga un bucle a través de StackTraceElement y obtenga el resultado deseado.
for (StackTraceElement ste : stackTraceElements )
{
//do your stuff here...
}
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
2015-07-23 08:09:07
Puede usar la utilidad jstack si desea verificar la pila de llamadas actual de su proceso.
Usage:
jstack [-l] <pid>
(to connect to running process)
jstack -F [-m] [-l] <pid>
(to connect to a hung process)
jstack [-m] [-l] <executable> <core>
(to connect to a core file)
jstack [-m] [-l] [server_id@]<remote server IP or hostname>
(to connect to a remote debug server)
Options:
-F to force a thread dump. Use when jstack <pid> does not respond (process is hung)
-m to print both java and native frames (mixed mode)
-l long listing. Prints additional information about locks
-h or -help to print this help message
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-24 09:24:16
Usé las respuestas de arriba y añadí formato
public final class DebugUtil {
private static final String SEPARATOR = "\n";
private DebugUtil() {
}
public static String formatStackTrace(StackTraceElement[] stackTrace) {
StringBuilder buffer = new StringBuilder();
for (StackTraceElement element : stackTrace) {
buffer.append(element).append(SEPARATOR);
}
return buffer.toString();
}
public static String formatCurrentStacktrace() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
return formatStackTrace(stackTrace);
}
}
Obtener stacktrace:
StackTraceElement[] ste = Thread.currentThread().getStackTrace();
Stacktrace de impresión (JAVA 9+):
Arrays.asList(ste).stream().forEach(System.out::println);
Stacktrage de impresión (JAVA 7):
StringBuilder sb = new StringBuilder();
for (StackTraceElement st : ste) {
sb.append(st.toString() + System.lineSeparator());
}
System.out.println(sb);
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
2018-08-22 11:50:23
Este es un post antiguo, pero aquí está mi solución :
Thread.currentThread().dumpStack();
Más información y más métodos allí : http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html
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-25 03:14:51
System.out.println(Arrays.toString(Thread.currentThread().getStackTrace()));
Esto le ayudará a imprimir seguimiento de pila sin bucle.
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-06-06 11:15:46