I am using log4j2 programmatically without a configuration file, but configuring it in code. I'm trying to use the log4j2 RollingFileAppender
to save the last 10 log files. I tried limiting the file size using the SizeBasedTriggeringPolicy
. The size limitation works but it doesn't create old log files and just keeps deleting and writing to the one original 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 didn't manage to find a lot of examples configuring the logging with java but i need to for my application. The example from where I took most of the code is here http://logging.apache.org/log4j/2.x/manual/customconfig.html (the second code part).
Why doesn't it create/save old log files?