【发布时间】:2016-06-13 13:42:56
【问题描述】:
我想写一篇关于实现 ErrorHandler 的 Java 类的日志。我的课程用于处理来自读取 xml 文件的错误。 我在网站上尽我所能,但我不明白为什么这段代码将日志文件留空。 此外,我不明白如何在我的应用程序中管理记录器。最好的做法是什么?您是否建议只有一个或多个日志文件?我将不得不记录多个错误处理程序:您是否建议将所有日志代码放入错误处理程序类?我应该为洞应用程序实现记录器吗?
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
class XmlErrorHandler implements ErrorHandler {
private static final Logger LOGGER = Logger.getLogger( XmlErrorHandler.class.getName() );
FileHandler fileHandler;
public XmlErrorHandler() {
try {
fileHandler = new FileHandler("./xml.log");
LOGGER.addHandler(fileHandler);
SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void error(SAXParseException e) {
log(Level.SEVERE, "Error", e);
}
public void fatalError(SAXParseException e) {
log(Level.SEVERE, "Fatal Error", e);
}
public void warning(SAXParseException e) {
log(Level.WARNING, "Warning", e);
}
private void log(Level level, String message, SAXParseException e) {
int line = e.getLineNumber();
int col = e.getColumnNumber();
String publicId = e.getPublicId();
String systemId = e.getSystemId();
message = message + ": " + e.getMessage() + ": line=" + line + ", col=" + col + ", PUBLIC=" + publicId
+ ", SYSTEM=" + systemId;
LOGGER.log(level, message);
}
}
编辑: 我要做的就是初始化日志:
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new XmlErrorHandler());
【问题讨论】: