Erase log files dated after a week using log4j

1

In my application I use the log4j library to generate system-wide logs. 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 deletes the old files that already have more than a week, because if my system stays running for a long time it is not possible to occupy much memory, because the application that I am developed is to be used on very old machines.

Is there any solution to this? I added the MaxFileSize and MaxHistory properties and it did not work.

    
asked by anonymous 05.02.2014 / 14:42

1 answer

3

Solution # 1 - Change to RollingFileAppender

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

Example:

log4j.appender.file.MaxBackupIndex=7

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

Solution # 2 - Use your own implementation

If you really need to keep DaylyRollingFileAppender you can 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 in a Script Scheduled on the Operating System

A final alternative is to schedule ( cron ) the daily cleaning of the old logs. This issue of SOEN I found a command that you could use:

find /path/to/logs -type f -mtime +7 -exec rm -f {} \;
    
05.02.2014 / 15:25