Reputation: 4231
For a rarely occurring condition in a method which is called from different sites, I'd like to have the stack trace in the log. The exceptional conditions are note detected via exceptions, that is, there is no try-catch.
The only way I'm aware if is to use a fake exception, like this:
static void logWithStacktrace(Logger logger, Priority p, String msg) {
try {
throw new AssertionError();
} catch (AssertionError e) {
logger.log(p, msg, e);
}
}
Is there a good way to do this without raising an exception? Maybe there is there a log4j feature I've overlooked? I'm looking for a solution that formats the stack trace as in real exception messages - ideally it would end up as a <log4j:throwable>
element in the XML log file. Using Thread.getStackTrace
and formatting it myself doesn't let me do that.
I'm aware that "rarely occurring" sort of screams for the code to be refactored to use exceptions. On the other hand, all I would do with the exceptions is to log them, since the problems are not really errors but an indication of questionable API usage. So it seems sort of contrived not to log them directly.
Upvotes: 0
Views: 370
Reputation: 670
Several of the log4j methods accept a Throwable object. A Throwable contains a snapshot of the execution stack of its thread at the time it was created. You should be able to use this as follows:
static void logWithStacktrace(Logger logger, Priority p, String msg) {
logger.log(p, msg, new Exception());
}
Upvotes: 1
Reputation: 670
You could try the following:
Thread.currentThread().getStackTrace();
This returns an array of StackTraceElement that you can loop round and process as required. Just note that the first element is usually the getStackTrace() call, so you probably want to skip it.
Upvotes: 0