1
votes

I use following log4j RollingFile appender in my webapp.

<Appenders>
    <RollingFile name="logFile"
                 fileName="${env:SYSTEM_LOGS}/${env:LOG_FILE_NAME}.log" immediateFlush="true"
                 filePattern="${env:SYSTEM_LOGS}/${env:LOG_FILE_NAME}.log.%d{yyyy_MM_dd.HH_mm_ss}.%i">
        <PatternLayout pattern="%d{yyyyMMdd-HHmmss.SSS}|%X{username}|%-5p|%t| %-100m (%c{1})%n"/>
        <Policies>
            <OnStartupTriggeringPolicy/>
        </Policies>
    </RollingFile>
</Appenders>

With filePattern="${env:SYSTEM_LOGS}/${env:LOG_FILE_NAME}.log.%d{yyyy_MM_dd.HH_mm_ss}.%i", when log is rolled over, old file gets renamed to a filename with an index number (specified with %i), so all old files should get renamed and should be preserved.

I rollover the log programmatically with following code.

org.apache.logging.log4j.Logger logManagerLogger = LogManager.getLogger();
Map<String, org.apache.logging.log4j.core.Appender> appenders = ((org.apache.logging.log4j.core.Logger) logManagerLogger).getAppenders();
appenders.forEach((appenderName, appender) -> {
    if (appender instanceof RollingFileAppender) {
        LOGGER.info("Switching log for appender " + appenderName);
        ((RollingFileAppender) appender).getManager().rollover();
    }
});

But, after 7 rollovers, the existing file gets removed (not renamed according to the specified filePattern) and log is continued in a new file.

What could be the issue here?

2

2 Answers

1
votes

set DefaultRolloverStrategy(default is 7), In your config will be:

    <Appenders>
    <RollingFile name="logFile"
                 fileName="${env:SYSTEM_LOGS}/${env:LOG_FILE_NAME}.log" immediateFlush="true"
                 filePattern="${env:SYSTEM_LOGS}/${env:LOG_FILE_NAME}.log.%d{yyyy_MM_dd.HH_mm_ss}.%i">
        <PatternLayout pattern="%d{yyyyMMdd-HHmmss.SSS}|%X{username}|%-5p|%t| %-100m (%c{1})%n"/>
        <Policies>
            <OnStartupTriggeringPolicy/>
        </Policies>
        <DefaultRolloverStrategy max="100"/>
    </RollingFile>
</Appenders>

now, it will have 100 log file to rollover.

1
votes

If you want unlimited rollingfile,

According to Log4j2 documentation, from release 2.8, it can be done by setting fileIndex attribute to nomax. For example:

<DefaultRolloverStrategy fileIndex="nomax" />