在记录器上滚动时不会创建新文件
我拥有自动化基础架构,可以通过编程方式使用log4j和sslf4j创建日志, 我的代码在运行时创建并滚动了附加程序
这是我创建文件附加程序的方式。
private static synchronized void createFileAppender(String testName, Logger logger, String filename,
String fileNamePattern, PatternLayout logLayout) throws IOException {
org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) logger;
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) coreLogger.getContext();
Configuration configuration = context.getConfiguration();
if (configuration.getAppender(testName) == null) {
System.out.println(">>>> Create new appender for test: " + testName);
RollingFileAppender fileAppender = RollingFileAppender.newBuilder().withFileName(filename)
.withFilePattern(fileNamePattern).withLayout(logLayout).withName(testName)
.withConfiguration(configuration)
.withPolicy(OnStartupTriggeringPolicy.createPolicy(0))
.withAppend(true)
.build();
fileAppender.getManager().setRolloverStrategy(DefaultRolloverStrategy.
createStrategy("10", "0", "10", null, null, true, configuration));
File f = new File(fileAppender.getFileName());
if (!f.exists()) {
System.out.println("Log file creation failed, retrying");
} else {
System.out.println("Log file path " + f.getAbsolutePath());
}
// fileAppender.setName(testName);
fileAppender.start();
configuration.addAppender(fileAppender);
LoggerConfig loggerConfig = new LoggerConfig(testName, Level.ALL, false);
loggerConfig.addAppender(fileAppender, Level.ALL, null);
configuration.addLogger(testName, loggerConfig);
context.updateLoggers(configuration);
}
}
这是我将其翻转的方式。
public static void rollOverLog() {
String testName = getTestLogName();
Logger logger = LogManager.getLogger(testName);
org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) logger;
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) coreLogger.getContext();
Configuration configuration = context.getConfiguration();
RollingFileAppender fileAppender = (RollingFileAppender) configuration.getAppender(testName);
if (fileAppender != null) {
fileAppender.getManager().rollover();
}
}
问题是当我将鼠标悬停在文件上时,该文件将被删除并重新创建 但以前的内容丢失了。