Close log files

This project was handed over to me, so I know little about it. There is a method that uses log (java.util.logging.Logger) and it creates two log files:

First file: fileName.log

Second file: fileName.log.lck

On Linux, when I do lsof , I see these two files as open. How to close these two files?

The reason I want to close these files is because this method runs several times a day, and after a couple of weeks the number of open files reaches the limit (about 1000), and at this point our system stops working. When we restart our process (the "Job Controller" that does the logging), the number of open log files goes to 0 and runs again.

This is what was done for 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 did not work

 finally{ Handler[] handler = log.getHandlers(); for(Handler h: handler){ h.close(); } } 
+4
source share
2 answers

First decision

If you do not want to change your code, use: How to send java.util.logging to log4j? java.util.logging.Logger for logging using SLF4J?

I am using log4j or logback . Both have a Rolling File Appender (old files deleted) or a Date / Time File appender.

Second solution

For logging, the best use is a sliding 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 a global file handler can be added.

+1
source

I just use:

 LogManager.getLogManager().reset(); 

this will lead to the cancellation of all the settings of your log (path to the log file, file name template, formatter ...), but it will stop using the logger to close the lock file and release the logger to

+5
source

Source: https://habr.com/ru/post/1439262/


All Articles