Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate log files based on time rather than size in Log4j?

Tags:

java

log4j

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)

like image 413
DivideByHero Avatar asked Nov 10 '09 21:11

DivideByHero


People also ask

How do I force a rotation in syslog?

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.

What is log4j rotation?

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.

What is the service used to rotate log files automatically?

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.

What is used to rotate log files monthly?

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.


1 Answers

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.

like image 186
Rob Hruska Avatar answered Sep 27 '22 19:09

Rob Hruska