I want to log the first stack frame which is visible from within my own code. Is it possible to walk a stack trace from a Throwable - something similar to StackWalker.walk(...)
I want to log the first stack frame which is visible from within my own code. Is it possible to walk a stack trace from a Throwable - something similar to StackWalker.walk(...)
You can stream the StacktraceElements:
Arrays.stream(throwable.getStackTrace().forEach(element ->{
if(element.getClassName().startsWith("your.package"){
logger.info(element.toString());
}
});
The best solution is to stream the results of Throwable.getStackTrace()
I know you can stream the array, but this will cause performance overhead.
In fact, it won't. The overheads of capturing the stack frames and turning them into an array of StackFrameElement is incurred when fillInStackTrace() is called. This happens during the instantiation of the Throwable (exception) object; i.e. before you throw it.
Basically, you have already taken the performance overhead of creating the array ... before you decide if you want to stream the stack frames or not.
On the flipside, it is possible to instantiate a Throwable (via a subclass) with the writableStackTrace argument set to false. That inhibits the call to fillInStackTrace. The net result is that no stackframes will be captured ... and there would be nothing to stream.
(And you can't change the mind. If the stackframes don't get captured when the Throwable is instantiated, they will be discarded as the stack is unwound during propagation of the exception.)
The most correct way is to pay the penalty and stream the Throwable.getStackTrace()...
This will though come with performance issues as the jvm must create all elements in the stack trace (not just the ones you want)...
If paying this performance overhead is not an option, you should "walk the stack" using the StackWalker from the java 9 stack walking api... This stack will deviate from the exception stack trace, and this needs to be considered when walking the stack...