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