How to set up log4j to automatically delete old logs on a schedule?
To regularly delete old logs, you can use a combination of log4j’s RollingFileAppender and TimeBasedRollingPolicy.
Firstly, in the log4j configuration file, redirect the log output to a file using the RollingFileAppender configuration. For example:
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/path/to/log/file.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
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
The configuration above directs the logging output to the file /path/to/log/file.log, with a maximum file size of 10MB and a maximum backup index of 10. This means that when the log file reaches 10MB, it will automatically rotate and keep a maximum of 10 backup files.
Next, you can use the TimeBasedRollingPolicy to automatically delete old logs based on a specified time interval. For example:
log4j.appender.file.rollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.file.rollingPolicy.FileNamePattern=/path/to/log/file-%d{yyyy-MM-dd}.log
log4j.appender.file.rollingPolicy.ActiveFileName=/path/to/log/file.log
log4j.appender.file.rollingPolicy.PurgeInterval=1
The above configuration will rotate files based on time, generating a new log file every day with the format /path/to/log/file-yyyy-MM-dd.log, and setting the active file as /path/to/log/file.log. Additionally, the cleanup interval for log files is set to every 1 day, meaning that log files from 1 day ago will be deleted every day.
With the above settings, you can achieve the function of automatically deleting old logs at scheduled times.