【发布时间】:2014-11-12 10:11:59
【问题描述】:
在下面的代码中,异常记录使用
logger.error("error", exceptionType.getMessage);
&
logger.error("error", exceptionType);
使用logger.error("error", exceptionType); 记录异常消息和堆栈跟踪。我认为使用 logger.error("error", exceptionType); 是首选选项,因为它会记录堆栈跟踪。但是我遇到了两种方法。是否有理由使用logger.error("error", exceptionType.getMessage); 而不是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);
}
输出:
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)
【问题讨论】:
-
这取决于你。你对日志有什么兴趣?你想记录堆栈跟踪还是只记录一条消息?