Friday 21 December 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...