定期java日志记录

时间:2012-07-26 11:35:40

标签: java.util.logging

我可以使用配置文件根据时间间隔刷新所有日志。搜索了很多。没找到任何。捷径是我们自己使用Timer并冲洗所有记录器。但是想知道configuraiton文件是否允许它。

1 个答案:

答案 0 :(得分:2)

LogManager文档中介绍了配置文件选项。这时,唯一的办法就是通过配置文件来使用' config'选项安装自定义代码以刷新所有记录器并执行计时器管理。如果需要访问JVM生命周期,可以创建一个自定义处理程序,忽略所有日志记录,但监听构造函数和关闭方法调用。

public class FlushAllHandler extends Handler {

    private final ScheduledExecutorService ses;
    private final Future<?> task;

    public FlushAllHandler() {
        //TODO: Look these up from the LogManager.
        super.setLevel(Level.OFF); //Ignore all published records.
        ses = Executors.newScheduledThreadPool(1);
        long delay = 1L;
        TimeUnit unit = TimeUnit.HOURS;
        task = ses.scheduleWithFixedDelay(new Task(), delay, delay, unit);
    }

    @Override
    public void publish(LogRecord record) {
        //Allow a trigger filter to kick off a flush.
        if (isLoggable(record)) {
            ses.execute(new Task());
        }
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
        super.setLevel(Level.OFF);
        task.cancel(false);
        ses.shutdown();
        try {
            ses.awaitTermination(30, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        ses.shutdownNow();
    }

    private static class Task implements Runnable {

        Task() {
        }

        @Override
        public void run() {
            final ArrayList<Handler> handlers = new ArrayList<>();
            final LogManager manager = LogManager.getLogManager();
            synchronized (manager) { //avoid ConcurrentModificationException
                final Enumeration<String> e = manager.getLoggerNames();
                while (e.hasMoreElements()) {
                    final Logger l = manager.getLogger(e.nextElement());
                    if (l != null) {
                        Collections.addAll(handlers, l.getHandlers());
                    }
                }
            }

            //Don't hold LogManager lock while flushing handlers.
            for (Handler h : handlers) {
                h.flush();
            }
        }
    }
}