Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.logging.logger create multiple log files by adding number after log filename

Tags:

java

logging

i have a problem of rotation of log filename when using java.util.logging.logger in tomcat.

private Logger LOGGER = Logger.getLogger(MyClass.class.getName());
private FileHandler fh = null; 
Log log = new Log();

private void writeLog(String terminalId, String date_time, String msg){
    log.isExists();
    fh =  new FileHandler(log.fullPath(), true);
    fh.setLevel(Level.INFO);
    fh.setFormatter(new MyLogFormatter());
    LOGGER.addHandler(fh);

    LOGGER.setUseParentHandlers(false);
    LOGGER.setLevel(Level.INFO);
    LOGGER.info("Terminal: " + terminalId);
    LOGGER.info("Time: " + date_time);
    LOGGER.info("message: " + msg);
}

public test() {
    writeLog(mapXML.get("terminalId"), mapXML.get("date_time"), "successful");
}

In the above code, the log.fullPath() is like "/usr/desktop/2015-05-13.log"

After i execute test() multiple times, multiple files such as

2015-05-13.log, 2015-05-13.log.1, 2015-05-13.log.2, 2015-05-13.log.3

are generated.

In the 2015-05-13.log, it contains the total messages, and the file with number only contains the message of that execution.

I know if restarting tomcat after each execution of test(), only 2015-05-13.log is created.

But i can not restart tomcat after each execution. So how to let it generate only one log file?

like image 386
Will Avatar asked Oct 24 '25 04:10

Will


1 Answers

This is coming late but am still posting for those who might find this relevant.

The problem is because you didn't close FileHandler fh after writing. The first log file created remains locked and not available, as a result, a new file is then created and appended a number to avoid conflict.

Simply add fh.close(); after LOGGER.info("message: " + msg); to close the handler.

like image 102
Victor Anuebunwa Avatar answered Oct 26 '25 19:10

Victor Anuebunwa