我在没有配置文件的情况下以编程方式使用log4j2,但在代码中进行配置。我尝试使用log4j2 RollingFileAppender
来保存最后10个日志文件。我尝试使用SizeBasedTriggeringPolicy
限制文件大小。大小限制有效,但它不会创建旧的日志文件,只是不断删除和写入一个原始日志文件。
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();
}
我没有设法找到很多使用java配置日志记录的示例,但我需要为我的应用程序。我从中获取大部分代码的示例是http://logging.apache.org/log4j/2.x/manual/customconfig.html(第二个代码部分)。
为什么不创建/保存旧日志文件?
答案 0 :(得分:3)
尽管这是一个老问题,但其他人可能觉得它很有用,我相信这是因为
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);
应该是
RollingFileAppender.createAppender(dir + "log\\test.log", dir + "log\\test-%i.log",
"true", "File", "false", "128", "true", policy, strategy, layout, (Filter) null, "false", "false", (String) null, config);
第三个参数是append选项 https://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/appender/RollingFileAppender.html