我如何在Java中获得当前堆栈跟踪,就像在。net中,你可以做environment。stacktrace ?
我找到了Thread.dumpStack(),但这不是我想要的-我想要得到堆栈跟踪,而不是打印出来。
我如何在Java中获得当前堆栈跟踪,就像在。net中,你可以做environment。stacktrace ?
我找到了Thread.dumpStack(),但这不是我想要的-我想要得到堆栈跟踪,而不是打印出来。
当前回答
我有一个实用工具方法,返回一个字符串与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));
}
其他回答
try {
}
catch(Exception e) {
StackTraceElement[] traceElements = e.getStackTrace();
//...
}
or
Thread.currentThread().getStackTrace()
也许你可以试试这个:
catch(Exception e)
{
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
e.printStackTrace(pw);
String errorDetail = writer.toString();
}
字符串'errorDetail'包含了堆栈跟踪。
如果希望检查进程的当前调用堆栈,可以使用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
托尼,作为对公认答案的评论,给出了似乎是最好的答案,实际上回答了OP的问题:
Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );
... OP没有询问如何从异常的堆栈跟踪中获取字符串。尽管我是Apache Commons的忠实粉丝,但当有像上面这么简单的东西时,使用外部库是没有逻辑理由的。
我使用了上面的答案并添加了格式
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);
}
}