Here is my pretty hacky way around it. It works by default if you do not use format strings and should work if you use g and u format strings in the file name, but not others.
public class FriendlyFileHandler extends FileHandler {
private static Object[] flushLock = new Object[0];
private String pattern;
public FriendlyFileHandler(String pattern, int maxLogLengthInBytes, int count) throws IOException,
SecurityException {
super(pattern, maxLogLengthInBytes, count);
this.pattern = pattern;
}
public synchronized File getCurrentLogFile() {
synchronized(flushLock) {
flush();
final String patternRegex =
pattern.replaceAll("%[gu]", "\\d*") +
"(\\.\\d*)?$";
final Pattern re = Pattern.compile(patternRegex);
final Matcher matcher = re.matcher("");
final File basedir = new File(pattern).getParentFile();
final File[] logs = basedir.listFiles(new FileFilter() {
@Override
public boolean accept(final File pathname) {
matcher.reset(pathname.getAbsolutePath());
return matcher.find();
}
});
return findMostRecentLog(logs);
}
}
private File findMostRecentLog(File[] logs) {
if (logs.length > 0) {
long mostRecentDate = 0;
int mostRecentIdx = 0;
for (int i = 0; i < logs.length; i++) {
final long d = logs[i].lastModified();
if (d >= mostRecentDate) {
mostRecentDate = d;
mostRecentIdx = i;
}
}
return logs[mostRecentIdx];
}
else {
return null;
}
}
@Override
public synchronized void flush() {
synchronized(flushLock) {
super.flush();
}
}
}
source
share