Print java stack trace from anywhere

Need to know which code calls a specific location? Dump the stack trace:

1
2
3
4
import org.apache.commons.lang3.exception.ExceptionUtils;

// ...somewhere in your method:
LOG.trace(ExceptionUtils.getStackTrace(new Throwable()));

You’re constructing a Throwable just to capture the current stack — you’re not throwing it. ExceptionUtils.getStackTrace turns the captured frames into a multi-line String that’s safe to hand to a logger. Make sure your log config has trace level enabled for whichever logger LOG belongs to, otherwise the line silently does nothing.


A few useful additions.

When this beats a breakpoint. You’d reach for this over a debugger when (a) you’re chasing a bug that only shows up in production, (b) the call happens in async / event-driven code where breakpoints are awkward, or (c) a method is called from many places and you want to know which path is firing. Sprinkle a few of these in, run the workload, then read the log.

No Apache Commons? Stdlib will do. ExceptionUtils lives in org.apache.commons.lang3, which is a separate dependency. If you don’t have it on the classpath you can fall back to plain JDK:

1
2
3
4
5
6
7
8
9
10
// Option 1 — quick and dirty, writes to stderr (not your logger):
new Throwable().printStackTrace();

// Option 2 — get the trace as a String you can log:
import java.io.StringWriter;
import java.io.PrintWriter;

StringWriter sw = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(sw));
LOG.trace(sw.toString());

Java 9+: StackWalker is the modern API. If you actually want to inspect the frames programmatically (instead of just dumping a blob of text), use StackWalker — it’s lazy, so it doesn’t eagerly materialize every frame the way new Throwable().getStackTrace() does:

1
2
3
4
5
6
7
import java.lang.StackWalker;
import java.lang.StackWalker.StackFrame;
import java.util.stream.Collectors;

String trace = StackWalker.getInstance()
        .walk(s -> s.map(StackFrame::toString).collect(Collectors.joining("\n")));
LOG.trace(trace);

For a one-line debug print though, the original Apache Commons one-liner is still hard to beat. 🪵

This entry was posted in java. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


8 × nine =