在下面的代码中,使用记录异常
logger.error("error", exceptionType.getMessage);
和
logger.error("error", exceptionType);
使用logger.error("error", exceptionType);
记录异常消息和stacktrace。我认为使用usinglogger.error("error", exceptionType);
是首选选项,因为它会记录stacktrace。但是我遇到过两种方法。是否有理由使用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)
当错误消息足够详细时,完整的堆栈跟踪可能会在日志中添加不必要的详细信息。例如,您实际上不需要查看FileNotFoundException的跟踪:记录文件名和错误消息就足以知道无法打开哪个文件以及原因。
在外部进程读取日志文件的系统中,诸如堆栈跟踪之类的多行消息也可能会出现问题。如果消息和日志行之间存在一对一的对应关系,则日志解析器将变得更易于编写。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句