log4j配置文件错误检测

时间:2010-10-13 18:25:28

标签: java validation configuration log4j

我目前正在使用log4j编写记录器。一旦我加载了log4j.properties或log4j.xml文件,我就想知道是否有办法检测记录器配置文件是否有效。如果它无效,我希望改为加载默认设置(位于另一个文件中)。

由于

2 个答案:

答案 0 :(得分:2)

我们通过在加载配置之前重定向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();
    }
}

答案 1 :(得分:1)

您只能尝试手动检查是否存在记录器。

http://svn.apache.org/viewvc/logging/log4j/trunk/src/main/java/org/apache/log4j/LogManager.java?view=markup

喜欢:LogManager.exists(“你的记录器名称”);

此外,您可以检查您的xml是否有效,并根据DTD验证它。

但“有效”日志文件的定义是什么?如果它唯一的语法基于使用DTD验证并检查属性文件是否格式良好。

如果文件有特定的星座,则使用上述手动方法。

希望有所帮助, 基督教