I am using log4j in my Java application.
I want to config both of maxsize (max is 1Mb) and auto delete after 15 days.
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=15
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
But it seems that in log4j can not config both of 2 my requirements, right?
How i can do it?
Thank all.
Your configuration is fine, to test it change MaxFileSize to 1KB and run following code:
public class LogTest {
static Logger log = Logger.getLogger("LogTest");
public static void main(String[] args)
{
PropertyConfigurator.configure("log4j.properties");//file should be in classpath
for (int i = 0; i < 20000; i++)
log.info("test");
System.out.println("Done");
}
}
Once it completes, you should be having total 16 files loging.txt and loging.txt.1 to loging.txt.15
You can create a batch file for the file deletion purpose ... the contents of the batch file will be as follows
cd "C:\<folder-location>\
del *.log
You can create a scheduler entry to run this file every 15 days... this way it will delete all log files after 15 days. (moreover using batch file you can also create a zip of log file as backup and keep it safe in some other location ... this is something you cannot do using log4j at all )
TO keep files as a zip backup (using 7-zip)
C:\Program Files\7-Zip\7z.exe a -tzip C:\B\ZipFile.zip C:\A\*.*
This will copy all files from folder A to B in a zip file.
Keeping maxsize is already done by you in the log4j configuration file.