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

com.alibaba.dts.client.executor.logcollector.LocalLogCleaner Maven / Gradle / Ivy

package com.alibaba.dts.client.executor.logcollector;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.joda.time.DateTime;

import com.alibaba.dts.common.logger.SchedulerXLoggerFactory;
import com.alibaba.dts.common.logger.innerlog.Logger;

/**
 *
 * @author xiaomeng.hxm
 */
public class LocalLogCleaner extends AbstractLogCleaner {
    private static final Logger LOGGER = SchedulerXLoggerFactory.getLogger(LocalLogCleaner.class);
    private static final int CLEAN_DAYS_BEFORE = 7;  //删除7天之前的日志

    private ScheduledExecutorService logCleanES = Executors
            .newScheduledThreadPool(1, new ThreadFactory() {
                int index = 0;
                @Override
                public Thread newThread(Runnable runnable) {
                    index++;
                    return new Thread(runnable, "DTS-LOCAL_LOG_CLEANER-thread-" + index);
                }
            });

    @Override
    public void init() {
        logCleanES.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                DateTime now = DateTime.now();
                try {
                    File file = new File(LocalLogCollector.DIR_PREFIX);
                    if (file.exists()) {
                        File[] children = file.listFiles();
                        for (File child : children) {
                            DateTime dt = new DateTime(child.getName());
                            if (dt.isBefore(now.withTimeAtStartOfDay().minusDays(CLEAN_DAYS_BEFORE))) {
                                deleteAllFilesOfDir(child);
                            }
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("[LocalLogCleaner] log clean error: ", e);
                }

            }
        }, 300, 60*60*24, TimeUnit.SECONDS); //每天跑一次

        LOGGER.info("[LocalLogCleaner] stared.");
    }

    public static void deleteAllFilesOfDir(File path) {
        if (!path.exists())
            return;
        if (path.isFile()) {
            path.delete();
            return;
        }
        File[] files = path.listFiles();
        for (File file : files) {
            deleteAllFilesOfDir(file);
        }
        path.delete();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy