I am using java.util.logging.Logger Class for logging in my application. I have added FileHandler so that the application log is stored directly in log.txt file.
But for some reason, after the application is terminated the log is far from complete. On cmd, I can see all the statements but they are never appended to the file.
I have set FileHandler to the Logger by:
private void setLogger() {
try {
FileHandler hand = new FileHandler("log/log.txt", true);
hand.setFormatter(new SimpleFormatter());
Logger log = Logger.getLogger(ImageRename.MAIN_LOG);
//log.setUseParentHandlers(false);
log.addHandler(hand);
log.setLevel(Level.ALL);
} catch (IOException e) {
System.out.println("Could Not set logger");
}
}
Any problem with flushing? How to solve it? Thanks.
PS: On debugging, I have noticed that in between
Logger.getLogger(ImageRename.MAIN_LOG).getHandlers().length
returns 0. Where as it should return 1. Initially it was printing 1, but somewhere down the line it becomes zero.
The problem is … garbage collection.
What is happening is likely the following:
Logger.getLogger(ImageRename.MAIN_LOG);Logger.getLogger(ImageRename.MAIN_LOG);and expect to get the same logger.You can avoid this by two measures:
logging.propertiesfor configuration. When creating the logger, the Java logging API will consult the configuration, and thus recreate it appropriately.Use static references. This is a best practise anyway. Equip each class with a logger:
While the class is loaded it then should not be garbage collected AFAICT.