简体   繁体   English

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

[英]Java.util.logger new file every day

I am using java.util.logging framework to implement logging in my JSF application. 我正在使用java.util.logging框架来实现我的JSF应用程序中的日志记录。 I have successfully done implementing this, but however I have a new requirement to rotate the logs and create a new log file for each day. 我已经成功地完成了这项工作,但是我有一个新的要求,即每天轮换日志并创建一个新的日志文件。

I am not able to figure out how this can be implemented. 我无法弄清楚如何实施。 Any hints on implementation would be highly appreciated. 任何有关实施的提示都将受到高度赞赏。 Thanks. 谢谢。

This is how I have configured my logger: 这就是我配置记录器的方式:

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

Since you are using code to setup your FileHandler then you can add code to close and recreate the FileHandler using the '%g'. 由于您使用代码来设置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);
}

If you want it to work automatically you can simply create a proxy handler for the FileHandler to handle closing and recreating files each day. 如果您希望它自动运行,您只需为FileHandler创建一个代理处理程序 ,以便每天处理关闭和重新创建文件。

Java.util.logging does not support rotating on a daily basis, see this bug report: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6350749 Java.util.logging不支持每天轮换,请参阅此错误报告: http//bugs.java.com/bugdatabase/view_bug.do?video_id = 6350749

Alternatively, you could use logback, log4j or log4j2 and slf4j to tunnel JUL (see http://www.slf4j.org/legacy.html#jul-to-slf4j ). 或者,您可以使用logback,log4j或log4j2和slf4j来隧道JUL(请参阅http://www.slf4j.org/legacy.html#jul-to-slf4j )。 All of the mentioned frameworks support date-based file rotation. 所有提到的框架都支持基于日期的文件轮换。

HTH, Mark HTH,马克

Create a task that executes every day at midnight using ScheduledThreadPoolExecutor and in the task dispose and close the current FileHandler and then create a new one with the updated file name. 使用ScheduledThreadPoolExecutor创建一个每天午夜执行的任务,并在任务dispose中关闭当前的FileHandler,然后使用更新的文件名创建一个新的任务。

Something like this should work: 这样的事情应该有效:

public class DailyLogger {

private static Logger logger;
private static FileHandler fh;

public static Logger getLogger() {
    if(logger == null){
        initLogger();

        ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor)Executors.newScheduledThreadPool(1); 
        // Create a task for one-shot execution using schedule()
        Runnable renameLoggerFile = new Runnable(){
//              int countRuns = 0;  // For testing only
            @Override
            public void run() {
                fh.flush();
                fh.close();

                try {
                    fh = createFilehandler(new java.sql.Date(System.currentTimeMillis()).toString());
//                      fh = createFilehandler(new java.sql.Date(System.currentTimeMillis()).toString()+"_"+countRuns++); // for testing

                    SimpleFormatter formatter = new SimpleFormatter();

                    fh.setFormatter(formatter);  
                    logger.addHandler(fh);
                    logger.warning("Runnable executed, new FileHandler is in use!");
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }               
        };

        Calendar c = Calendar.getInstance();
        long now = c.getTimeInMillis();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        long passed = now - c.getTimeInMillis();
        long secondsPassedToday = passed / 1000;
        long secondsInDay = 86400;

        TimeUnit timeUnit = TimeUnit.SECONDS;
 //         sch.scheduleAtFixedRate(renameLoggerFile, 5, 10, timeUnit); // for testing
        long initialDelay = secondsInDay - secondsPassedToday;
        long relaunchPeriod = secondsInDay;
        sch.scheduleAtFixedRate(renameLoggerFile, initialDelay, relaunchPeriod, timeUnit);

    }
    return logger;
}
private static FileHandler createFilehandler(String dateForName) throws SecurityException, IOException{
    String folder = "log";
    File fileFolder = new File(folder);
    // Create folder log if it doesn't exist
    if(!fileFolder.exists()){
        fileFolder.mkdirs();
    }

    dateForName = folder + File.separator + dateForName + ".log";

    boolean appendToFile = true;

    return new FileHandler(dateForName, appendToFile);  
}
private static void initLogger(){
    String folder = "log";
    File fileFolder = new File(folder);
    // Create folder "log" if it doesn't exist
    if(!fileFolder.exists()){
        fileFolder.mkdirs();
    }

    logger = Logger.getLogger("DailyLogger");  

    try {  
        // This block configure the logger with handler and formatter
        boolean appendToFile = true;
        fh = new FileHandler(folder + File.separator + new java.sql.Date(System.currentTimeMillis()) + ".log", appendToFile);  

        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);  

        // the following statement is used to log any messages
        logger.info("DailyLogger initialized...");  

    } catch (SecurityException e) {  
        logger.warning("Problem at initializing logger... " + e.getMessage());
    } catch (IOException e) {  
        logger.warning("Problem at initializing logger... " + e.getMessage());
    }  
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM