Question

I am using Log4j2, some beta-10 version or so.

It's easy to log a stack trace when you have an exception:

} catch (Exception ex) {
  log.error("Doing stuff went wrong", ex);
}

Suppose though there is no Throwable object available - I just realized there is a problem and want to log an error:

 if (stuffIsWrong()) {
   log.error("Stuff went wrong");
 }

How can I tell Log4j2 to log a stack trace beginning in the current method?

Was it helpful?

Solution

Just create a new Exception

if (stuffIsWrong()) {
    log.error("Stuff went wrong", new Exception("Stracktracegenerator"));
}

OTHER TIPS

Stack trace of any method can be printed by the following code:

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste);
}

just check your condition and if it meets then print the stack trace in logs

I've had a similar need for a stack trace even though nothing "went wrong". I understand your reluctance to use an exception even though nothing went wrong.

In my case this was a temporary problem, I needed to find out via which sequence of calls a certain method was invoked.

To separate this stack trace from "real" exceptions I created a class extending Exception called NoProblemJustShowingStackTrace, but any name that clarifies your intention would be fine. A good name helps a little, but as developers we are so used to seeing stack traces only when a "real" exception is thrown/caught that it will still be confusing to the people reading the log. Best remove this code once the temporary problem is resolved.

Note that you don't throw this exception, all you do is create the object and pass it to the logger method.


A more permanent alternative solution is to use a pattern layout with location information, like %location, %line, %file, %class, %method. Note that this will have a large impact on performance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top