0

I am creating a logger by using log4j's RollingFileAppender. Currently the roll back is happening based on MaxFileSize and MaxBackupIndex. I need to keep the generated log files for 14 days.

log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender    
log4j.appender.LOGFILE.File=/path/mylog.log 
log4j.appender.LOGFILE.MaxFileSize=50MB 
log4j.appender.LOGFILE.MaxBackUpIndex=30
soufrk
  • 825
  • 1
  • 10
  • 24
  • Does [this](https://stackoverflow.com/questions/3683364/how-to-configure-log4j-to-only-keep-log-files-for-the-last-seven-days) help ? – soufrk Jun 08 '18 at 10:12

1 Answers1

0

You can use the DailyRollingFileAppender to rollover based on time. But, it can only,

Is is possible to specify monthly, weekly, half-daily, daily, hourly, or minutely rollover schedules.

and doesn't seem to have a an option to specify the number of backups. Also,

DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender.

Ex:

log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingAppender.File=app.log
log4j.appender.RollingAppender.DatePattern='.'yyyy-MM-dd

You can then clear out old files, through a cron job, as mentioned here.Check out the log4j Documentation once.

Antho Christen
  • 1,369
  • 1
  • 10
  • 21
  • Thanks . Can we use same RollingFileAppender and add rolling policy (TimeBasedRollingPolicy) in that case how to set filenamepattern?? – Harsha Jayan Jun 08 '18 at 11:57
  • Sure, but that's not a default part of `log4j` 1 its a part of `log4j extras`. – Antho Christen Jun 08 '18 at 14:19
  • Just add `log4j.appender.LOGFILE.rollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy log4j.appender.LOGFILE.FileNamePattern=/path/mylog-.%d{yyyyMMdd}.log` remeber to add the extras jar.Also If you're open to changing loggin frameowrks i'd recomend log4j2/logback, log4j1 ended a long time back. – Antho Christen Jun 08 '18 at 15:12