Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
2 answers
It's not clear where this stack trace comes from (either from an exception or the current thread), but it doesn't matter, the way to do it is the same.
Both Exception
's and Thread
's have the getStackTrace()
method. For the current thread, you can use Thread.currentThread().getStackTrace()
, but you can call the method for any other thread as well.
In either case, the getStackTrace
method will return an array of StackTraceElement
's. Just remind that, for threads, it'll return a zero-length array if the thread has not started, has started but has not yet been scheduled to run by the system, or has terminated.
Anyway, once you have the array, it's very straighforward to log the first N lines:
int limit = 5; // number of elements to log
// Get the stack trace from an exception
// or use Thread.currentThread().getStackTrace() to get from the current thread
// or simply thread.getStackTrace() to get from any other thread
StackTraceElement[] elements = exception.getStackTrace();
// just in case the array has fewer elements than the limit
int len = Math.min(elements.length, limit);
for (int i = 0; i < len; i++) {
log.error(elements[i].toString());
}
0 comment threads
Throwable:
...
Arrays.stream(throwable.getStackTrace())
.limit(yourIntLimit)
.forEach(stackTraceElement ->
log.error(stackTraceElement.toString()));
...
Thread:
...
Arrays.stream(Thread.currentThread().getStackTrace())
.limit(yourIntLimit)
.forEach(stackTraceElement ->
log.error(stackTraceElement.toString()));
...
Contributing:
Thread.currentThread(),
thank you mikea,
https://stackoverflow.com/a/21706861
0 comment threads