Search code examples
spring-bootlog4j2syslog

Delete rolloed over log files in log4j2 after a threshold size is reached


I have migrated from logback to log4j2 since the syslog appender in logback did not support the RFC5424 format.

But now I want to roll over the log files up to a certain threshold and delete the older files.

This option is available in logback as "totalSizeCap". Below is the snippet from the logback.xml

    rollingPolicy
        class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <!-- roll over daily and when the file reaches 100 MB, max of 7 days or 3GB threshold -->
        <fileNamePattern>/data/storage/log/cms.%d{yyyy-MM-dd}.%i.Logs.gz
        </fileNamePattern>
        <maxFileSize>100MB</maxFileSize>
        <maxHistory>7</maxHistory>
        <totalSizeCap>3GB</totalSizeCap>
    </rollingPolicy>

Here the files are rolled over once their size reaches 100 MB and zipped. Also, max history of 7 days is maintained and older logs are deleted. But if the size of these files exceeds 3GB with in the 7days period, even then the old logs are removed.

I did not find the equivalent configuration in log4j2.xml

below is my log4j2.xml which does not work

<RollingFile name="RollingFile"
                 fileName="/data/storage/log/cms.log"
                 filePattern="/data/storage/log/cms.%d{yyyy-MM-dd}.%i.Logs.gz">
        <PatternLayout pattern="${LOG_PATTERN}" />
        <Policies>
            <SizeBasedTriggeringPolicy size="100 MB" />
            <TimeBasedTriggeringPolicy />
        </Policies>
        <DefaultRolloverStrategy max ="100" totalSizeCap="3GB">
            <Delete basePath="/data/storage/log/" maxDepth="2">
                <IfFileName glob="*/cms*.Logs.gz" />
                <IfLastModified age="P7D" />
            </Delete>
        </DefaultRolloverStrategy>
    </RollingFile>
    <Syslog name="Syslog" format="RFC5424" host="127.0.0.1" port="514"
            protocol="UDP" appName="CMS" enterpriseNumber="25979" facility="LOCAL0" />

please help.


Solution

  • I'm afraid you can't do the deletion of old log files based on time for version 2.19.0. Instead, you can get your old files deleted by using size-based rollover strategies.

    In versions 2.5 and above, you can delete log files based on time. If you want to use version 2.5 and above, the answer here will be useful to you.