如何获取 Java 中当前的堆栈跟踪?

发布于 2024-07-26 11:03:01 字数 326 浏览 6 评论 0原文

如何在 Java 中获取当前的堆栈跟踪,就像在 .NET 中一样Environment.StackTrace

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

How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?

I found Thread.dumpStack() but it is not what I want - I want to get the stack trace back, not print it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

难得心□动 2024-08-02 11:03:01

您可以使用 Thread.currentThread ().getStackTrace()

返回一个 StackTraceElement 的数组 代表程序的当前堆栈跟踪。

You can use Thread.currentThread().getStackTrace().

That returns an array of StackTraceElements that represent the current stack trace of a program.

不爱素颜 2024-08-02 11:03:01
StackTraceElement[] st = Thread.currentThread().getStackTrace();

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

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

如果重要的话,将为您当前的方法指定一个明确的位置。

StackTraceElement[] st = Thread.currentThread().getStackTrace();

is fine if you don't care what the first element of the stack is.

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

will have a defined position for your current method, if that matters.

凉月流沐 2024-08-02 11:03:01
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste + "\n");
}
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste + "\n");
}
少女情怀诗 2024-08-02 11:03:01

托尼,作为对已接受答案的评论,给出了似乎是最佳答案,实际上回答了OP的问题

Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );

......OP确实没有 询问如何从Exception的堆栈跟踪中获取String。 尽管我是 Apache Commons 的超级粉丝,但当有像上面这样简单的东西时,就没有逻辑理由使用外部库。

Tony, as a comment to the accepted answer, has given what seems to be the best answer which actually answers the OP's question:

Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );

... the OP did NOT ask how to get a String from the stack trace from an Exception. And although I'm a huge fan of Apache Commons, when there is something as simple as the above there is no logical reason to use an outside library.

℉服软 2024-08-02 11:03:01
Thread.currentThread().getStackTrace();

从 JDK1.5 开始可用。

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

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

is available since JDK1.5.

For an older version, you can redirect exception.printStackTrace() to a StringWriter() :

StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();
剩一世无双 2024-08-02 11:03:01

您可以使用 Apache 的 commons 来实现:

String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);

You can use Apache's commons for that:

String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
与酒说心事 2024-08-02 11:03:01

在 Android 上,一个更简单的方法是使用这个:

import android.util.Log;
String stackTrace = Log.getStackTraceString(exception); 

On android a far easier way is to use this:

import android.util.Log;
String stackTrace = Log.getStackTraceString(exception); 
¢蛋碎的人ぎ生 2024-08-02 11:03:01

另一种解决方案(只有 35 31 个字符):

new Exception().printStackTrace();   
new Error().printStackTrace();

Another solution (only 35 31 characters):

new Exception().printStackTrace();   
new Error().printStackTrace();
云醉月微眠 2024-08-02 11:03:01

要获取所有线程的堆栈跟踪,您可以使用 jstack 实用程序、JConsole 或发送kill -quit 信号(在 Posix 操作系统上)。

但是,如果您想以编程方式执行此操作,您可以尝试使用 ThreadMXBean:

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);

for (ThreadInfo info : infos) {
  StackTraceElement[] elems = info.getStackTrace();
  // Print out elements, etc.
}

如前所述,如果您只需要当前线程的堆栈跟踪,那就容易得多 - 只需使用 Thread.currentThread().getStackTrace()代码>;

To get the stack trace of all threads you can either use the jstack utility, JConsole or send a kill -quit signal (on a Posix operating system).

However, if you want to do this programmatically you could try using ThreadMXBean:

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);

for (ThreadInfo info : infos) {
  StackTraceElement[] elems = info.getStackTrace();
  // Print out elements, etc.
}

As mentioned, if you only want the stack trace of the current thread it's a lot easier - Just use Thread.currentThread().getStackTrace();

谢绝鈎搭 2024-08-02 11:03:01

Java 9 中有一种新方法:

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 );
}

In Java 9 there is a new way:

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 );
}
小红帽 2024-08-02 11:03:01

我建议这

  Thread.dumpStack()

是一种更简单的方法,并且具有在可能根本不存在问题时不实际构造异常或可抛出的优点,并且更切题。

I suggest that

  Thread.dumpStack()

is an easier way and has the advantage of not actually constructing an exception or throwable when there may not be a problem at all, and is considerably more to the point.

会傲 2024-08-02 11:03:01

愚蠢的我,它是 Thread.currentThread().getStackTrace();

Silly me, it's Thread.currentThread().getStackTrace();

⊕婉儿 2024-08-02 11:03:01

获取堆栈跟踪:

StackTraceElement[] ste = Thread.currentThread().getStackTrace();

打印堆栈跟踪(JAVA 8+):

Arrays.asList(ste).forEach(System.out::println);

打印堆栈跟踪(JAVA 7):

StringBuilder sb = new StringBuilder();

for (StackTraceElement st : ste) {
    sb.append(st.toString() + System.lineSeparator());
}
System.out.println(sb);

Getting stacktrace:

StackTraceElement[] ste = Thread.currentThread().getStackTrace();

Printing stacktrace (JAVA 8+):

Arrays.asList(ste).forEach(System.out::println);

Printing stacktrage (JAVA 7):

StringBuilder sb = new StringBuilder();

for (StackTraceElement st : ste) {
    sb.append(st.toString() + System.lineSeparator());
}
System.out.println(sb);
花开柳相依 2024-08-02 11:03:01

用番石榴串起来:

Throwables.getStackTraceAsString(new Throwable())

To string with guava:

Throwables.getStackTraceAsString(new Throwable())
盗梦空间 2024-08-02 11:03:01

我有一个实用程序方法,它返回带有堆栈跟踪的字符串:

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));
}

I have a utility method that returns a string with the 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();
}

And just logit like...

... 
catch (FileNotFoundException e) {
    logger.config(getStackTrace(e));
}
青衫儰鉨ミ守葔 2024-08-02 11:03:01
try {
}
catch(Exception e) {
    StackTraceElement[] traceElements = e.getStackTrace();
    //...
}

或者

Thread.currentThread().getStackTrace()
try {
}
catch(Exception e) {
    StackTraceElement[] traceElements = e.getStackTrace();
    //...
}

or

Thread.currentThread().getStackTrace()
赠佳期 2024-08-02 11:03:01

也许你可以尝试这个:

catch(Exception e)
{
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    e.printStackTrace(pw);
    String errorDetail = writer.toString();
}

字符串“errorDetail”包含堆栈跟踪。

Maybe you could try this:

catch(Exception e)
{
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    e.printStackTrace(pw);
    String errorDetail = writer.toString();
}

The string 'errorDetail' contains the stacktrace.

只是一片海 2024-08-02 11:03:01
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

数组的最后一个元素表示堆栈的底部,这是序列中最近的方法调用。

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

循环 StackTraceElement 并获得您想要的结果。

for (StackTraceElement ste : stackTraceElements ) 
{
    //do your stuff here...
}
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

loop through StackTraceElement and get your desired result.

for (StackTraceElement ste : stackTraceElements ) 
{
    //do your stuff here...
}
纵情客 2024-08-02 11:03:01

如果您想检查进程的当前调用堆栈,可以使用 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

You can use jstack utility if you want to check the current call stack of your process.

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
两相知 2024-08-02 11:03:01

我使用了上面的答案并添加了格式

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);
    }
}

I used answers from above and added formatting

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);
    }
}
小红帽 2024-08-02 11:03:01

对于那些只想将当前堆栈跟踪记录到日志中的人来说,我会选择:

getLogger().debug("Message", new Throwable());

干杯

For people, who just want to get the current stacktrace to their logs, I would go with:

getLogger().debug("Message", new Throwable());

Cheers

匿名的好友 2024-08-02 11:03:01

您还可以使用异常来打印堆栈,而不用费力地放置新行字符:

Exception e = new Exception();
e.setStackTrace(Thread.currentThread().getStackTrace());
loggr.info(e);

You can also use exception to print stack instead of taking pain of putting new line char:

Exception e = new Exception();
e.setStackTrace(Thread.currentThread().getStackTrace());
loggr.info(e);
烟酉 2024-08-02 11:03:01

这是一篇旧帖子,但这是我的解决方案:

Thread.currentThread().dumpStack();

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

This is an old post, but here is my solution :

Thread.currentThread().dumpStack();

More info and more methods there :
http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文