Wednesday, May 30, 2012

Get current stack trace in Java


Something like Environment.StackTrace in .Net.



BTW, Thread.dumpStack() is not what I want - I want to get the stacktrace back, not print it out.



Source: Tips4all

10 comments:

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

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

    ReplyDelete
  2. Thread.currentThread().getStackTrace();


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

    new Throwable().getStackTrace();


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

    ReplyDelete
  3. 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();

    ReplyDelete
  4. for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste + "\n");
    }

    ReplyDelete
  5. 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();

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

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


    or

    Thread.currentThread().getStackTrace()

    ReplyDelete
  8. You can use apache's commons for that:

    String fullStackTrace = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);

    ReplyDelete
  9. A far easier way is to use this:

    String stackTrace = Log.getStackTraceString(exception);

    ReplyDelete
  10. 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));
    }

    ReplyDelete