此函数将获取与给定前缀匹配的最新日志文件。您不需要知道日志写入的目录。
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;
}