I use Log4j with the RollingFileAppender
to create a log rotation based on size.
How can I configure it to log to each file for a certain amount of time before rotating?
For example, so that each log file contains one hour of logs, rotating at the top of each hour?
I configure Log4j programatically in Java using a Properties
object (as opposed to a log4j.properties
file)
If you want to rotate /var/log/syslog it needs to be listed in a logrotate config file somewhere, and you just run logrotate . If it rotated recently, then logrotate -f to force it to do it again. So, you need that in a file, normally either /etc/logrotate. conf or as a file snippet in /etc/logrotate.
You can roll and delete log4j log files by time intervals or by file size. File size log rotation is controlled by CompositeRollingAppender. Time interval log rotation is controlled by CompositeRollingAppender and a Java property in the common services start file.
The logrotate program is a log file manager. It is used to regularly cycle (or rotate) log files by removing the oldest ones from your system and creating new log files. It may be used to rotate based on the age of the file or the file's size, and usually runs automatically through the cron utility.
logrotate is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large. Normally, logrotate is run as a daily cron job.
You probably want to use a DailyRollingFileAppender. To roll them hourly, for example, you'd use a DatePattern of '.'yyyy-MM-dd-HH
. For a log4j.properties file:
log4j.appender.myAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myAppender.DatePattern='.'yyyy-MM-dd-HH
...
Or for your programmatic configuration:
DailyRollingFileAppender appender = new DailyRollingFileAppender();
appender.setDatePattern("'.'yyyy-MM-dd-HH");
Logger root = Logger.getRootLogger();
root.addAppender(appender);
Unfortunately, using a DailyRollingFileAppender means that you can't limit the file size - this could be problematic if you have tons of logs in the given rolled period.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With