Java – log4j configuration file error detection

I am writing a recorder using log4j Once I load log4j Properties or log4j XML file, I wonder if there is a way to check whether the recorder configuration file is valid If it doesn't work, I want to load the default settings (in another file)

thank you

Solution

By redirecting the system before loading the configuration Err and check whether the error is recorded in the stream to solve this problem:

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();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>