2010-10-13 45 views
6

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

感谢

+1

是的,这是该死的讨厌,我同意。不过,我认为你不能这样做。 – skaffman 2010-10-13 19:24:23

+0

我做了很多的搜索,没有任何东西出现。我希望堆栈溢出可能会给我一个答案,但我想我只需要依靠良好的用户输入,如果他们决定改变文件。感谢您的答复! :) – user459811 2010-10-13 22:53:47

回答

1

你只能尽量手动检查记录仪是存在与否。

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

像:LogManager.exists( “您的记录器名称”);

此外,您可以检查您的XML是否有效,并验证它是否符合DTD。

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

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

希望帮助, 基督教

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(); 
    } 
}