Log4j configuration file error detection

I am currently writing a logger using log4j. As soon as I load the log4j.properties file or the log4j.xml file, I was wondering if there is a way to determine if the log configuration file is valid. If this is not the case, I was hoping to load the default setting (located in another file).

thanks

+6
java validation configuration log4j
source share
2 answers

We solved this problem by redirecting System.err before loading the configuration and checking if errors were written 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(); } } 
+2
source share

You can only check manually for a log to exist or not.

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

Like: LogManager.exists ("your registrar name");

In addition, you can check if your xml is valid or not by checking it against DTD.

But what is the definition for a β€œvalid” log file? If its only syntax uses DTD checking and check if the properties file is in good format.

If the file is valid, if it has a specific constellation, use the manual approach above.

Hope this helps, Christian

+1
source share

All Articles