2015-01-08 156 views
1

我最近學習的是Java日誌記錄,在javadoc中,它說SimpleFormatter可以使用屬性「java.util.logging.SimpleFormatter.format」進行配置。java.util.logging.SimpileFormatter系統屬性配置

在下面的代碼中,我嘗試過使用System.setProperty()設置格式兩次,但它在第二次嘗試中似乎不起作用,下面的代碼中的「formatterB」仍將使用定義的格式「formatterA」。

這是什麼原因,謝謝。

public class Test { 
    public static void main(String[] args) { 
     try { 
      Logger loggerA = Logger.getLogger("A"); 
      System.setProperty("java.util.logging.SimpleFormatter.format", "A: %1$tc %2$s%n%4$s: %5$s%6$s%n"); // first attempt 
      Handler handlerA = new FileHandler("A.log", 0, 1, true); 
      SimpleFormatter formatterA = new SimpleFormatter(); 
      handlerA.setFormatter(formatterA); 
      loggerA.addHandler(handlerA); 
      loggerA.info("Logger A info message"); 

      Logger loggerB = Logger.getLogger("B"); 
      System.setProperty("java.util.logging.SimpleFormatter.format", "B: %1$tc %2$s%n%4$s: %5$s%6$s%n"); // second attempt 
      Handler handlerB = new FileHandler("B.log", 0, 1, true); 
      SimpleFormatter formatterB = new SimpleFormatter(); 
      handlerB.setFormatter(formatterB); 
      loggerB.addHandler(handlerB); 
      loggerB.info("Logger B info message"); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

回答

2

SimpleFormatter stores the format in a static field在類加載時存儲一次。該格式用於SimpleFormatter類的所有實例。

你必須推出自己的格式化類或類以支持多種格式。

+0

澄清了困惑,真的很有幫助:) – foolhunger