Issue
This project has been handed down to me, so I do not know much about it. There is a method where log (java.util.logging.Logger) is used and it creates two log files:
Second file: fileName.log.lck
In Linux when I do lsof
, I see these two files as open. How do I close these two files?
The reason why I want to close these files is this method is run multiple times a day and after couple of weeks the number of open files reaches a limit (around 1000), at which point our system stops working. When we restart our process ("Job Controller" which does the logging) the number of log files open goes to 0 and it works again.
This is what's been done to do logging
private static Logger log = Logger.getLogger(MyClass.class.getPackage().getName());
try{
log.logp(Level.SEVERE, "com.MyClass", "run", "It failed");
}
This is what I tried to do to close the files in the finally block but it didn't work
finally{
Handler[] handler = log.getHandlers();
for(Handler h: handler){
h.close();
}
}
Solution
First solution
If you do not want to modify your code use: How to send java.util.logging to log4j? java.util.logging.Logger to Logback using SLF4J?
I use log4j or logback. Both have Rolling File Appender (old files are removed) or Date/Time File appender.
Second solution
For logging the best usage is rolling file.
String filePattern = " fileName%.log";
int limit = 1000 * 1000; // 1 Mb
int numLogFiles = 3;
FileHandler fh = new FileHandler(filePattern, limit, numLogFiles);
// Add to logger
Logger logger = Logger.getLogger(MyClass.class.getPackage().getName());
logger.addHandler(fh);
I do not know if you can add globally file handler.
Answered By - Andrzej Jozwik Answer Checked By - David Marino (WPSolving Volunteer)