I use log4j2 programmatically without a configuration file, but I configure it in code. I am trying to use the log4j2 RollingFileAppender to save the last 10 log files. I tried to limit the file size using SizeBasedTriggeringPolicy . The size limit works, but it does not create old log files and simply deletes and writes to the same source log file.
public static void configLog() { String dir = System.getProperty("java.io.tmpdir") + "test\\"; final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build(); SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy("1KB"); DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("10", "0", null, null, config); RollingFileManager fileManager = RollingFileManager.getFileManager(dir + "log\\test.log", dir + "log\\test-%i.log", false, false, policy, strategy, null, layout, 128); policy.initialize(fileManager); RollingFileAppender appender = RollingFileAppender.createAppender(dir + "log\\test.log", dir + "log\\test-%i.log", "false", "File", "false", "128", "true", policy, strategy, layout, (Filter) null, "false", "false", (String) null, config); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("File", Level.INFO, null); AppenderRef[] refs = new AppenderRef[] { ref }; LoggerConfig loggerConfig = LoggerConfig.createLogger("true", Level.INFO, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, Level.INFO, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); }
I have not been able to find many examples of configuring logging using java, but I need for my application. An example from which I took most of the code is here http://logging.apache.org/log4j/2.x/manual/customconfig.html (second part of the code).
Why doesn't it create / save old log files?