Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j configuration file error detection

I'm currently writing a logger utilizing log4j. Once I load in a log4j.properties or a log4j.xml file, I was wondering if there was a way to detect if the logger configuration file is valid. If it isn't valid, I was hoping to load a default setting (that's located in another file) instead.

Thanks

like image 623
user459811 Avatar asked Oct 13 '10 18:10

user459811


1 Answers

We solved this problem by redirecting System.err before loading the configuration and checking if errors were logged to the stream:

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();
    }
}
like image 136
Björn Avatar answered Oct 02 '22 14:10

Björn