Friday, December 21, 2018

java - Fetch only first N lines of a Stack Trace



I have a Factory method that returns an object from a ID call.



Mock code:



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;
}


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?



Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...