javalog4j2rollingfileappender

log4j2 change Rolling file appender max files programmatically


I am working on an application that uses log4j2 (initializes the parameters using log4j2.xml) and loads the logger. When the application runs, I am required to programmatically override a few parameters such as changing the log level and rolling file appender properties. I am able to change the log level using

/**
         * @param logger Logger instance
         * @param level New log level to be applied on the logger instance
         */
        private void setLoggerLevel(Logger logger, Level level) {
            LoggerContext context = (LoggerContext) LogManager.getContext(false);
            Configuration config = context.getConfiguration();
            LoggerConfig loggerConfig = getLoggerConfig(logger.getName());


            Logger rootLogger = LogManager.getRootLogger();
            if(logger !=  rootLogger && loggerConfig != config.getLoggerConfig(rootLogger.getName()))
            {
                loggerConfig.setLevel(level);
                context.updateLoggers();
            }
        }

Now I tried to tackle the same problem using RollingFile appender's properties. However, I am stuck on how to modify the existing RollingFile appender's property

Logger applicationLogger = LogManager.getLogger(logName);

if (applicationAppender instanceof RollingFileAppender) {

    // Configure max properties of rolling file appender here
    if (maxLogFiles != null) {

        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        Configuration config = context.getConfiguration();
        // Copied code from lib
        DefaultRolloverStrategy newStrategy = DefaultRolloverStrategy.createStrategy(String.valueOf(maxLogFiles), null, null,
                String.valueOf(Deflater.DEFAULT_COMPRESSION), null, true, config);

        // How to modify the existing appender?

    }

}

What is the way to proceed with modifying the rolling file appender programmatically?


Solution

  • You are on the right track. After creating the new Strategy do:

    Appender appender = config.getAppender("MyRollingFile");
    if (appender instanceof RollingFileAppender) {
        ((RollingFileAppender) appender).getManager().setRolloverStrategy(newStrategy);
    }
    

    If you want to modify all the RollingFileAppenders then do:

    Map<String, Appender> appenders = config.getAppenders();
    for (Appender appender : appenders.values()) {
        if (appender instanceof RollingFileAppender) {
            ((RollingFileAppender) appender).getManager().setRolloverStrategy(newStrategy);
        }
    }