Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j2: log stack trace without an exception

Tags:

java

log4j2

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?

like image 397
vektor Avatar asked Apr 28 '14 09:04

vektor


Video Answer


2 Answers

Just create a new Exception

if (stuffIsWrong()) {
    log.error("Stuff went wrong", new Exception("Stracktracegenerator"));
}
like image 186
Absurd-Mind Avatar answered Nov 09 '22 09:11

Absurd-Mind


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.

like image 20
Remko Popma Avatar answered Nov 09 '22 09:11

Remko Popma