Good suggestion to log stack trace. But I have a different approach:
But what about: java.util.logging.Logger.throwing(String sourceClass, String sourceMethod, Throwable thrown).
I have never used this method, but I guess this might be what we need.
Cheers,
Cedric
Aaron Kagawa wrote:
Hey Guys,
In trying to figure out the error in DailyProjectUnitTest, I thought it would be a good idea to log the stack trace. We've talked about this issue a couple of weeks ago in a code review. The problem is that we all like to use Throwable.printStackTrace because it provides detailed information about the exception. However, the printStackTrace prints only to console and not to the log. To log the stack trace we would have to use the Throwable.getStackTrace, but that is a little hard to deal with.
I've came up with this simple solution. Does this implementation satisfy other developers' needs?
/** * Converts the Throwable.getStackTrace to a String representation for logging. This method * tries create a String that imitates the Throwable.printStackTrace as much as possible. * [EMAIL PROTECTED] throwable The Throwable exception. * [EMAIL PROTECTED] stackTrace An array of stack trace elements. * [EMAIL PROTECTED] A String containing the StackTrace. */ *public* String convertStackTraceToString(Throwable throwable, StackTraceElement[] stackTrace) { StringBuffer stackTraceStringBuffer = *new* StringBuffer(); stackTraceStringBuffer.append(throwable); *for* (*int* i = 0; i < stackTrace.length; i++) { StackTraceElement element = stackTrace[i]; stackTraceStringBuffer.append( "\n at " + element.toString()); } *return* stackTraceStringBuffer.toString(); }
Clients should do something like:
String stackTrace = serverProperties.convertStackTraceToString(e, e.getStackTrace()); logger.info(stackTrace);
thanks, aaron
