2011-05-09 67 views
12

我正在尋找一種方法來檢索webapp中的Tomcat日誌。在過去,我已經看到了在其他webapps中提供的這個功能,通常是將日誌轉儲到一個Servlet中。在webapp中以編程方式獲取tomcat日誌文件

我使用SLF4J(與log4j的)和Tomcat 6,我還沒有發現在Tomcat文檔相關的任何東西,雖然JMX API看起來像它可能會提供一些有用的東西?我並不太在意輸出是代表Web應用程序日誌還是整個Tomcat日誌,或者足夠了。

理想情況下,我希望的,不涉及刮從文件系統日誌的解決方案,但如果這是唯一的辦法,這將是巨大的,如果日誌目錄可能會在運行時計算...

回答

17

從文件系統中抓取日誌可能是最簡單的方法。您可以直接使用System.getProperty("catalina.base") + "/logs"以編程方式獲取日誌。

否則,你可以設置你的log4j的配置額外的附加器登錄到像JDBC,JMS,作家等無論是有道理的,你的應用程序。

+0

我嘗試了兩種方法,Tomcat日誌最適合我的要求。謝謝您的幫助! – seanhodges 2011-05-11 15:56:41

6

此功能將得到最新的日誌文件中匹配一個給定的前綴。您不需要知道日誌寫入的目錄。

public static File locateLogFile(final String prefixToMatch) { 
    File result = null; 
    Handler[] handlers = LogManager.getLogManager().getLogger("").getHandlers(); 
    try { 
     for(Handler handler : handlers) { 

      Field directoryField; 
      Field prefixField; 
      try { 
       //These are private fields in the juli FileHandler class 
       directoryField = handler.getClass().getDeclaredField("directory"); 
       prefixField = handler.getClass().getDeclaredField("prefix"); 
       directoryField.setAccessible(true); 
       prefixField.setAccessible(true); 
      } catch(NoSuchFieldException e) { 
       continue; 
      } 

      String directory = (String)directoryField.get(handler); 
      if(prefixToMatch.equals(prefixField.get(handler))) { 
       File logDirectory = new File( directory); 
       File[] logFiles = logDirectory.listFiles(new FileFilter() { 
        public boolean accept(File pathname) { 
         return pathname.getName().startsWith(prefixToMatch); 
        } 
       }); 
       if(logFiles.length == 0) continue; 
       Arrays.sort(logFiles); 
       result = logFiles[ logFiles.length - 1 ]; 
       break; 
      } 
     } 
    } catch(IllegalAccessException e) { 
     log.log(Level.WARNING, "Couldn't get log file", e); 
    } 
    return result; 
} 
相關問題