此功能將得到最新的日誌文件中匹配一個給定的前綴。您不需要知道日誌寫入的目錄。
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;
}
我嘗試了兩種方法,Tomcat日誌最適合我的要求。謝謝您的幫助! – seanhodges 2011-05-11 15:56:41