Determining Current Call Stack (For Diagnostic Purposes)

前端 未结 4 573
面向向阳花
面向向阳花 2020-11-27 15:26

For diagnostic purposes I sometimes need to store the call stack that lead to a given state transition (such as granting a lock, committing a transaction, etc.) so that when

相关标签:
4条回答
  • 2020-11-27 16:09

    There's a new option since JDK 9: StackWalker

    It isn't as expensive as Thread.currentThread().getStackTrace().

    see also How Expensive is Thread.getStackTrace()?

    0 讨论(0)
  • 2020-11-27 16:14

    I think you can get the same thing with:

    StackTraceElement[] cause = Thread.currentThread().getStackTrace();
    
    0 讨论(0)
  • 2020-11-27 16:21

    Well, you can improve it slightly by not actually throwing the exception.

    Exception ex = new Exception();
    ex.fillInStackTrace();
    StackTraceElement[] cause = ex.getStackTrace();
    

    Actually, I just checked: the constructor calls fillInStackTrace() already. So you can simplify it to:

    StackTraceElement[] cause = new Exception().getStackTrace();
    

    This is actually what Thread.getStackTrace() does if it's called on the current thread, so you might prefer using it instead.

    0 讨论(0)
  • 2020-11-27 16:27

    If you want it as a String and use Apache Commons:

    org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(new Throwable())
    
    0 讨论(0)
提交回复
热议问题