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

com.alibaba.schedulerx.worker.logcollector.LocalLogCleaner Maven / Gradle / Ivy

There is a newer version: 1.12.2
Show newest version
package com.alibaba.schedulerx.worker.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 com.alibaba.schedulerx.worker.domain.WorkerConstants;
import com.alibaba.schedulerx.worker.log.LogFactory;
import com.alibaba.schedulerx.worker.log.Logger;

import org.joda.time.DateTime;


/**
 *
 * @author xiaomeng.hxm
 */
public class LocalLogCleaner extends LogCleaner {
    private static final Logger LOGGER = LogFactory.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, "Schedulerx-log-clean-thread-" + index);
                }
            });

    @Override
    public void init() {
        logCleanES.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                DateTime now = DateTime.now();
                try {
                    File file = new File(WorkerConstants.LOCAL_LOG_COLLECTOR_DIR);
                    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 (Throwable 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 == null) {
            LOGGER.warn("path is null");
            return;
        }

        if (!path.exists()) {
            return;
        }

        if (path.isFile()) {
            path.delete();
            return;
        }

        File[] files = path.listFiles();
        if (files != null) {
            for (File file : files) {
                deleteAllFilesOfDir(file);
            }
        } else {
            LOGGER.warn("list files is null, path=" + path.getPath());
        }
        path.delete();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy