log4j2以编程方式更改Rolling file appender max files

时间:2016-06-13 19:36:39

标签: java log4j2 rollingfileappender

我正在使用一个使用log4j2的应用程序(使用log4j2.xml初始化参数)并加载记录器。当应用程序运行时,我需要以编程方式覆盖一些参数,例如更改日志级别和滚动文件追加器属性。我可以使用

更改日志级别
/**
         * @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();
            }
        }

现在我尝试使用RollingFile appender的属性来解决同样的问题。但是,我仍然坚持如何修改现有的RollingFile appender属性

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?

    }

}

以编程方式继续修改滚动文件追加程序的方法是什么?

2 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。创建新战略后:

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

如果要修改所有RollingFileAppender,请执行以下操作:

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

答案 1 :(得分:0)

rgoers的解决方案对我来说就像一种魅力。我只需要更改策略创建方法,因为 现在已弃用CreateStrategy。要创建我使用的新策略:

           DefaultRolloverStrategy newStrategy = DefaultRolloverStrategy
    .newBuilder()
    .withMax(String.valueOf(maxLogFiles))
    .withCompressionLevelStr(String.valueOf(Deflater.DEFAULT_COMPRESSION))                                                                
    .withFileIndex("min")
    .withConfig(config)
    .build();