Reputation: 21
I've got an application that runs every 15 minutes, 23 hours a day. Most of the time, it 'wakes' up, sees there is no data to process and closes. During the initialization and input data check, there are DEBUG log statements that write to the console only. Only once the application has found data to process does it write anything to a log file (INFO level and higher). Problem is, the 'no data to process' runs are creating empty log files, even though nothing is ever written to them. As this turns on almost 100 times a day, this behavior is undesirable.
I can easily implement a method to manually delete these files if they are unneeded, but this seems...hacky. Is there a way to make Log4j wait on creating the log file until something is actually written to it? Thanks!
Relevant portion of log4j.properties:
log4j.appender.myFileLogger=org.apache.log4j.RollingFileAppender
log4j.appender.myFileLogger.Append=false
log4j.appender.myFileLogger.File=D:/Imaging/myApp/logs/myApp_${current.date}.log
log4j.appender.myFileLogger.threshold=INFO
log4j.appender.myFileLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.myFileLogger.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Upvotes: 1
Views: 1430
Reputation: 11
There is an option in File appender called "createOnDemand" which could be of use:
createOnDemand boolean The appender creates the file on-demand. The appender only creates the file when a log event passes all filters and is routed to this appender. Defaults to false.
Upvotes: 1
Reputation: 21
If anyone else ever comes across this, here's how I 'solved' this:
if(deleteLog) {
FileAppender appender = (FileAppender)Logger.getRootLogger().getAppender("myFileLogger");
String path = appender.getFile();
Logger.shutdown();
Files.delete(Paths.get(path));
}
This still feels a bit hackish, but it works without needing extra config points or hard coded file paths. Make sure to call logger.shutdown() or else Log4j will still have an open handle on the file, throwing a "another process is using this file" error.
Basil Musa's answer provided the basis for this: https://stackoverflow.com/a/9480213/5780475
Upvotes: 0