In below code exceptions are logged using
logger.error("error", exceptionType.getMessage);
&
logger.error("error", exceptionType);
Using logger.error("error", exceptionType);
logs the exception message and stacktrace. I think using using logger.error("error", exceptionType);
is preferred option as it logs stacktrace. But I have encountered both ways methods. Is there a reason to use logger.error("error", exceptionType.getMessage);
instead of logger.error("error", exceptionType);
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExceptionTest {
public static void main(String args[]) {
try {
throwsException();
} catch (Exception e) {
System.out.println("1");
logger.error("error", e.getMessage());
}
try {
throwsException();
} catch (Exception e) {
System.out.println("2");
logger.error("error", e);
}
}
private static void throwsException() throws Exception {
throw new Exception();
}
private static Logger logger = LoggerFactory.getLogger(ExceptionTest.class);
}
Output :
1
12.11.2014 10:06:30 ERROR [xceptionTest.main():14] error
2
12.11.2014 10:06:30 ERROR [ExceptionTest.main():21] error
java.lang.Exception
at ExceptionTest.throwsException(ExceptionTest.java:26)
at ExceptionTest.main(ExceptionTest.java:18)