gpt4 book ai didi

java - log4j配置文件错误检测

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:33:17 25 4
gpt4 key购买 nike

我目前正在使用 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();
}
}

关于java - log4j配置文件错误检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3926758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com