How can I get the current stack trace in Java?

前端 未结 21 3107
耶瑟儿~
耶瑟儿~ 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:21

    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

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

    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 );
    }
    
    0 讨论(0)
  • 2020-11-22 00:22

    To string with guava:

    Throwables.getStackTraceAsString(new Throwable())
    
    0 讨论(0)
  • 2020-11-22 00:23
    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();
    
    0 讨论(0)
  • 2020-11-22 00:23

    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));
    }
    
    0 讨论(0)
  • 2020-11-22 00:24

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

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