java – log4j配置文件错误检测
发布时间:2020-05-25 16:52:53 所属栏目:Java 来源:互联网
导读:我正在使用log4j编写一个记录器.一旦我加载了log4j.properties或log4j.xml文件,我就想知道是否有办法检测记录器配置文件是否有效.如果它无效,我希望加载默认设置(位于另一个文件中). 谢谢 我们通过在加载配置之前重定向System.err并检查错误是否记录到流来解
|
我正在使用log4j编写一个记录器.一旦我加载了log4j.properties或log4j.xml文件,我就想知道是否有办法检测记录器配置文件是否有效.如果它无效,我希望加载默认设置(位于另一个文件中). 谢谢 解决方法我们通过在加载配置之前重定向System.err并检查错误是否记录到流来解决了这个问题:class ConfigurationLoader {
class Log4jConfigStderrStream extends ByteArrayOutputStream {
private int lineCount;
private StringBuilder output;
private PrintStream underlying;
public Log4jConfigStderrStream(PrintStream underlying) {
this.lineCount = 0;
this.output = new StringBuilder("");
this.underlying = underlying;
}
@Override
public void flush() throws IOException {
String[] buffer;
synchronized (this) {
buffer = this.toString().split("n");
super.flush();
super.reset();
for (int i = 0; i < buffer.length; i++) {
String line = buffer[i].replace("n","").replace("r","");
if (line.length() > 0) {
this.lineCount++;
this.output.append(line);
this.output.append("n");
}
}
}
}
public String getOutput() {
return this.output.toString();
}
public PrintStream getUnderlying() {
return this.underlying;
}
public boolean hasErrors() {
return this.lineCount == 0 ? false : true;
}
}
private String output;
public void flushOutput() {
if (!"".equals(this.output))
System.err.print(this.output);
}
public boolean loadConfiguration(String filename) {
Log4jConfigStderrStream confErr;
confErr = new Log4jConfigStderrStream(System.err);
System.setErr(new PrintStream(confErr,true));
LogManager.resetConfiguration();
DOMConfigurator.configure(filename);
System.setErr(confErr.getUnderlying());
this.output = confErr.getOutput();
return !confErr.hasErrors();
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
