I am just sharing the method that i am using to convert stacktrace to string. This stacktrace is then being used in AWS Lambda to log. There are two things i am mainly concerned about
private String convertStackTrace(Throwable throwable){
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
String stackTrace;
try {
throwable.printStackTrace(printWriter);
stackTrace = stringWriter.toString();
}
catch(Exception e){
logSelf("Error converting exception. Simple exception message will be logged");
stackTrace = throwable.getMessage();
} finally {
try {
stringWriter.flush();
stringWriter.close();
printWriter.flush();
printWriter.close();
} catch (Exception e){
logSelf("Error closing writers");
}
}
return stackTrace;
}
Here is logSelf method
private void logSelf(String error){
lambdaLogger.log(formatMessage(
this.getClass().getCanonicalName(), LOG_LEVEL_ERROR, error, null)
);
}
- Shall i be opening/closing those printwriters everytime an error is logged?
- Is it correct way to convert stacktrace to string?