Java.util.logger每天都有新文件

Sir*_*h V 7 java logging

我正在使用java.util.logging框架来实现我的JSF应用程序中的日志记录.我已经成功地完成了这项工作,但是我有一个新的要求,即每天轮换日志并创建一个新的日志文件.

我无法弄清楚如何实施.任何有关实施的提示都将受到高度赞赏.谢谢.

这就是我配置记录器的方式:

        myLogger = Logger.getLogger("info.aio");
        fileHandler = new FileHandler("aioinfo.log", 1048576, 100, true);
        fileHandler.setFormatter(new SimpleFormatter());
        myLogger.addHandler(fileHandler);
Run Code Online (Sandbox Code Playgroud)

jme*_*ens 5

由于您使用代码来设置FileHandler,因此您可以添加代码以关闭并使用'%g' 重新创建FileHandler.

public static void main(String[] args) throws Exception {
    //create aioinfo0.log.
    install();
    //rename aioinfo0.log to aioinfo1.log and create aioinfo0.log.
    install();
}

private static final Logger myLogger = Logger.getLogger("info.aio");
private static volatile FileHandler fileHandler;

private static void install() throws IOException {
    FileHandler fh = fileHandler;
    if (fh != null) {
        myLogger.removeHandler(fh);
        fh.close(); //Release any file lock.
    }

    fileHandler = rotate("aioinfo%g.log", 1048576, 100, true);
    fileHandler.setFormatter(new SimpleFormatter());
    myLogger.addHandler(fileHandler);
}

private static FileHandler rotate(String pattern, int limit, int count, boolean append) throws IOException {
    if (pattern == null) {
        LogManager m = LogManager.getLogManager();
        String p = FileHandler.class.getName();
        pattern = m.getProperty(p + ".pattern");
        if (pattern == null) {
            pattern = "%h/java%u.log";
        }
    }

    new FileHandler(pattern, 0, count, false).close(); //Trigger rotate.
    return new FileHandler(pattern, limit, count, append);
}
Run Code Online (Sandbox Code Playgroud)

如果您希望它自动运行,您只需为FileHandler 创建一个代理处理程序,以处理每天关闭和重新创建文件.