Delete log files with a date later than a week using log4j

Asked

Viewed 783 times

1

In my application I use the log4j library to generate the logs of the whole system. It is working correctly, I use the following settings:

Direct log messages to a log file

log4j.appender.file=org.apache.log4j.Dailyrollingfileappender log4j.appender.file.File=log/application.log log4j.appender.file.Datepattern='. 'yyyy-MM-dd log4j.appender.file.layout=org.apache.log4j.Patternlayout log4j.appender.file.layout.Conversionpattern=%d{dd-MM-yyyy,HH:mm:ss:SSS},%t,%-5p,%c{1}:%L-%m%n log4j.appender.file.Maxfilesize=50KB log4j.appender.file.Maxhistory=2

I would like to know if there is any property that erases old files that are already more than a week old, because if my system is running for a long time it is impractical to occupy a lot of memory, because the application I am developed is to be used on very old machines.

Is there a solution for this? I added the Maxfilesize and Maxhistory properties and it didn’t work.

1 answer

3


Solution #1 - Switch to RollingFileAppender

The class RollingFileAppender has the attribute MaxBackupIndex, which does exactly what you need, that is, limit log history to a certain number.

Example:

log4j.appender.file.MaxBackupIndex=7

Meanwhile, the DailyRollingFileAppender does not have this attribute. A solution would be to change the log type.

Solution #2 - Use your own implementation

If you really need to keep DaylyRollingFileAppender it is possible to create your next implementation of FileAppender. I found two links that teach you how to do this:

Note that I did not test the above solutions.

Solution #3 - Clean up a scheduled script in the Operating System

One last alternative is to schedule (cron) the daily cleaning of old logs. On this issue of SOEN found a command you could use:

find /path/to/logs -type f -mtime +7 -exec rm -f {} \;
  • 1

    Use Dailyrollingfileappender and I made my own implementation. Thank you @utluiz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.