Is there a way to dump a stack trace without throwing an exception in java?

前端 未结 10 1385
庸人自扰
庸人自扰 2020-12-04 07:37

I am thinking of creating a debug tool for my Java application.

I am wondering if it is possible to get a stack trace, just like Exception.printStackTrace()

相关标签:
10条回答
  • 2020-12-04 08:07

    The answer by Rob Di Marco is by far the best if you are happy to output to stderr.

    If you want to capture to a String, with new lines as per a normal trace, you could do this:

    Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );
    
    0 讨论(0)
  • 2020-12-04 08:08

    HPROF Java Profiler

    You don't even have to do this in the code. You can attach the Java HPROF to your process and at any point hit Control-\ to output heap dump, running threads, etc . . . without mucking up your application code. This is a bit outdated, Java 6 comes with the GUI jconsole, but I still find HPROF to be very useful.

    0 讨论(0)
  • 2020-12-04 08:11

    Notice that Thread.dumpStack() actually throws an exception:

    new Exception("Stack trace").printStackTrace();
    
    0 讨论(0)
  • 2020-12-04 08:12

    Yes, simply use

    Thread.dumpStack()
    
    0 讨论(0)
  • 2020-12-04 08:13

    If you want the trace for just the current thread (rather than all the threads in the system, as Ram's suggestion does), do:

    Thread.currentThread().getStackTrace()

    To find the caller, do:

    private String getCallingMethodName() {
        StackTraceElement callingFrame = Thread.currentThread().getStackTrace()[4];
        return callingFrame.getMethodName();
    }
    

    And call that method from within the method that needs to know who its caller is. However, a word of warning: the index of the calling frame within the list could vary according to the JVM! It all depends on how many layers of calls there are within getStackTrace before you hit the point where the trace is generated. A more robust solution would be to get the trace, and iterate over it looking for the frame for getCallingMethodName, then take two steps further up to find the true caller.

    0 讨论(0)
  • 2020-12-04 08:16

    You can also try Thread.getAllStackTraces() to get a map of stack traces for all the threads that are alive.​​​​​​

    0 讨论(0)
提交回复
热议问题