All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bidib.wizard.logback.CleanAtStartRollingFileAppender Maven / Gradle / Ivy

There is a newer version: 2.0.29
Show newest version
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);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy