我如何在Java中获得当前堆栈跟踪,就像在。net中,你可以做environment。stacktrace ?

我找到了Thread.dumpStack(),但这不是我想要的-我想要得到堆栈跟踪,而不是打印出来。


当前回答

如果希望检查进程的当前调用堆栈,可以使用jstack实用程序。

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

其他回答

我有一个实用工具方法,返回一个字符串与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();
}

然后就像这样…

... 
catch (FileNotFoundException e) {
    logger.config(getStackTrace(e));
}

这是一个老帖子,但这是我的解决方案:

Thread.currentThread().dumpStack();

更多信息和更多的方法: http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html

Thread.currentThread().getStackTrace();

从JDK1.5开始可用。

对于旧版本,你可以重定向exception.printStackTrace()到StringWriter():

StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();

你也可以使用异常来打印堆栈,而不是痛苦地输入新的行字符:

Exception e = new Exception();
e.setStackTrace(Thread.currentThread().getStackTrace());
loggr.info(e);
StackTraceElement[] st = Thread.currentThread().getStackTrace();

如果你不关心堆栈的第一个元素是什么,那就没问题。

StackTraceElement[] st = new Throwable().getStackTrace();

将有一个定义的位置为您当前的方法,如果这很重要。