How can I get the current stack trace in Java?

前端 未结 21 3108
耶瑟儿~
耶瑟儿~ 2020-11-21 23:49

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 -

相关标签:
21条回答
  • 2020-11-22 00:26

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

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

    0 讨论(0)
  • 2020-11-22 00:29

    You can use Apache's commons for that:

    String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
    
    0 讨论(0)
  • 2020-11-22 00:30

    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.

    0 讨论(0)
  • 2020-11-22 00:33
    try {
    }
    catch(Exception e) {
        StackTraceElement[] traceElements = e.getStackTrace();
        //...
    }
    

    or

    Thread.currentThread().getStackTrace()
    
    0 讨论(0)
  • 2020-11-22 00:33
    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...
    }
    
    0 讨论(0)
  • 2020-11-22 00:34

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题