org.bidib.wizard.logback.CleanAtStartRollingFileAppender Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bidibwizard-client Show documentation
Show all versions of bidibwizard-client Show documentation
jBiDiB BiDiB Wizard Client Application POM
package org.bidib.wizard.logback;
import java.io.File;
import java.io.FileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.RollingPolicy;
import ch.qos.logback.core.rolling.RollingPolicyBase;
import ch.qos.logback.core.rolling.helper.FileFilterUtil;
import ch.qos.logback.core.rolling.helper.FileNamePattern;
public class CleanAtStartRollingFileAppender extends RollingFileAppender {
@Override
public void start() {
if (!append) {
deleteBackupFiles();
}
super.start();
}
private void deleteBackupFiles() {
addInfo("Delete logfiles before start appender.");
try {
String currentFileName = super.getFile();
File currentFile = new File(currentFileName);
if (currentFile.exists()) {
addInfo("Delete the current file: " + currentFileName);
currentFile.delete();
}
final RollingPolicy triggeringPolicy = getRollingPolicy();
if (triggeringPolicy instanceof RollingPolicyBase) {
final RollingPolicyBase base = (RollingPolicyBase) triggeringPolicy;
Context context = getContext();
final FileNamePattern fileNamePattern = new FileNamePattern(base.getFileNamePattern(), context);
// no use checking if either fileName or fileNamePattern are null
if (fileNamePattern != null && fileName != null) {
String regex = fileNamePattern.toRegex();
addInfo("Current filename regex: " + regex);
// find the backup files and delete them
File dir = new File(fileName).getParentFile();
String path = dir.getPath();
path = FileFilterUtil.slashify(path);
FileFilter fileFilter = new RegexFileFilter(regex.substring(path.length() + 1));
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
}
}
catch (Exception ex) {
addWarn("Delete existing logfiles failed.", ex);
}
}
}