2016-07-01 21 views
0

我有一個工具運行在多個JVM中,但是會記錄到相同的%t(temp)目錄。我在logging.properties文件中使用%u(唯一)模式變量,以便每個實例都記錄到不同的日誌文件。如何輸出當前java.util.logging.Logger日誌文件名的名稱?

如果進程識別失敗(這是一個監視工具),它會發送一封電子郵件,我想附加遇到失敗的特定實例的日誌文件。但是,我如何獲得日誌文件路徑?如果這不是一個好的方法,也很樂意接受會是更好的方法。

+0

如果每個程序都記錄到不同的日誌文件夾或使用不同的日誌文件名稱/前綴,組織起來會不會更好? – Andreas

+0

感謝您的評論。這對我來說並不重要,因爲一旦通過電子郵件發送日誌文件就是「一次性」的。沒人會瀏覽日誌文件。無論如何,它看起來像我需要以編程的方式來做這件事,而不是簡單地通過日誌配置,所以最終他們會被組織起來。 – AndyJ

回答

0

有一個根據JDK-4798814 getFiles() needed for java.util.logging.FileHandler提交給Oracle的RFE涵蓋了這個。

如果您不使用安全管理員,您可以採取反思措施。

public class GetFileHandler extends FileHandler { 

    public GetFileHandler() throws IOException { 
     super(); 
    } 

    /** 
    * Gets the files used by this handler. Index zero is the file that is 
    * in use. 
    * 
    * @return a array of files. 
    * @throws IOException if there is an error. 
    * @throws SecurityException if not allowed. 
    */ 
    public File[] getFiles() throws IOException { 
     return GetFileHandler.getFiles(this); 
    } 

    private static File[] getFiles(FileHandler h) throws IOException { 
     try { 
      Field f = FileHandler.class.getDeclaredField("files"); 
      f.setAccessible(true); 
      synchronized (h) { 
       return ((File[]) f.get(h)).clone(); 
      } 
     } catch (ReflectiveOperationException roe) { 
      throw new IOException(roe); 
     } 
    } 
} 

請記住,此解決方案可能與文件旋轉競爭。如果FileHandler源代碼發生更改,它也可能會中斷。

如果你不需要旋轉,那麼你總是可以擴展StreamHandler並提供一個已知的文件位置。

public class KnownFileHandler extends StreamHandler { 

    private final File file; 

    public KnownFileHandler() throws IOException { 
     String v = LogManager.getLogManager().getProperty(getClass().getName() +".name"); 
     if(v == null) { 
      v = "knownfilehandler.log"; 
     } 
     file = new File(v); 
     this.setOutputStream(new FileOutputStream(file)); 
    } 


    public File getFile() { 
     return this.file; 
    } 
} 

如果監控工具支持傳入的TCP連接,則java.util.logging.SocketHandler將發送所有的日誌信息監測工具的方式,然後你可以有監控工具決定存儲或發送日誌數據。

+0

非常有幫助,謝謝你的無數建議! – AndyJ

相關問題