Determining Current Call Stack (For Diagnostic Purposes)

浪尽此生 提交于 2019-12-17 04:58:45

问题


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 something goes wrong later I can find out who originally triggered the state transition.

Currently, the only way I am aware of to retrieve the call stack looks like the following code snippet, which I consider terribly ugly:

StackTraceElement[] cause;
try {
  throw new Exception();
} catch (Exception e) {
  cause = e.getStackTrace();
}

Does somebody know of a better way to accomplish this?


回答1:


I think you can get the same thing with:

StackTraceElement[] cause = Thread.currentThread().getStackTrace();



回答2:


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.




回答3:


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

org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(new Throwable())


来源:https://stackoverflow.com/questions/706292/determining-current-call-stack-for-diagnostic-purposes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!