2010-10-13 46 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(); 
    } 
}