javalog4jlog-rotation

How to rotate logs on every server shutdown in log4j2


Right now I am rotating logs using log4j2 if it reaches 2000MB and time based i.e. every hour with following logic:-

<RollingRandomAccessFile name="test"
            fileName="${sys:log4j.logPath}/testlog" filePattern="${sys:log4j.logPath}/test-%d{yyyy-MM-dd-HH}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{ISO8601} %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="1990 MB" />
                <TimeBasedTriggeringPolicy />
            </Policies>
        </RollingRandomAccessFile>

I also want to rotate logs when server shutdown. what configuration I have to add to the following ?

I have used OnStartupTriggeringPolicy to rotate logs on shutdown. But logs gets rotated after made a single request with server restart.

But I want my logs rotated when server shutdown. Is there a way to do it ?


Solution

  • I have found the solution for above issue. Following code works for me.

    Add 'shutdownHook="disable"' in log4j.xml

    <Configuration status="WARN" shutdownHook="disable">
    

    Method for rollover():-

    public class RollOverLog4j {
    
        public static void rollover() {
            public final Logger logger = LogManager.getLogger("test");
    
            Map<String, Appender> appenders = ((org.apache.logging.log4j.core.Logger) logger).getAppenders();
            Iterator<Entry<String, Appender>> appenderIterator = appenders.entrySet().iterator();
            while (appenderIterator.hasNext()) {
                Appender appender = appenderIterator.next().getValue();
                if (appender instanceof RollingRandomAccessFileAppender) {
                    ((RollingRandomAccessFileAppender) appender).getManager().rollover();
                }
            }
        }
    
    }
    

    Call rollover() on server stop:-

    RollOverLog4j.rollover()
    // shutting down log4j manually
    Configurator.shutdown((LoggerContext) LogManager.getContext());
    

    Note:- rollover() is not public method in log4 2.3 version. So use latest version 2.6 to make it work.