仅获取堆栈跟踪的前N行 [英] Fetch only first N lines of a Stack Trace
本文介绍了仅获取堆栈跟踪的前N行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Factory方法,它从ID调用中返回一个对象。
I have a Factory method that returns an object from a ID call.
模拟代码:
public static Object getById(String id) {
Object o = CRUD.doRecovery(Class, id);
if(o == null) {
printLogMessage("recovery by ID returned Null: " + id);
// would really like to show only a few lines of stack trace.
}
return o;
}
如何只显示堆栈跟踪的前N行(所以我知道方法的调用者)而不将整个堆栈跟踪转储到日志上或不得不依赖外部库?
How can I show only the first N lines of the stack trace (so I know the caller of the method) without dumping the whole stack trace on the log or having to rely on external libs?
推荐答案
我根据你的要求假设,你没有例外处理。在这种情况下,您可以从以下位置获取当前堆栈跟踪:
I'm assuming from what you are asking, that you don't have an exception to deal with. In which case you can get the current stack trace from:
StackTraceElement[] elements = Thread.currentThread().getStackTrace()
这将告诉你几乎所有你需要知道的关于你来自哪里的代码。
This will tell you pretty much everything you need to know about where you've come from in the code.
这篇关于仅获取堆栈跟踪的前N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文