我需要创建一个滚动文件附加器,并在运行时使用log4j2设置日志文件的数量。因此我使用以下代码来实现这一点:
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
.withMax("4")
.withMin("1")
.withFileIndex("max")
.withConfig(config)
.withCompressionLevelStr(Deflater.NO_COMPRESSION + "")
.build();
PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config)
.withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%5p] %pid --- %-40.40logger{39} : %m%n%wEx")
.build();
RollingFileAppender appender = RollingFileAppender.newBuilder().setConfiguration(config)
.withName("TraceFileAppender")
.withLayout(layout)
.withFileName("log.log")
.withFilePattern("log.%d{yyyy-MM-ddHHmmSSS}.log")
.withPolicy(SizeBasedTriggeringPolicy.createPolicy("20KB")
.withStrategy(strategy)
.build();
appender.start();
config.addAppender(appender);
LoggerConfig loggerConfig = config.getRootLogger();
loggerConfig.setLevel(Level.toLevel("DEBUG"));
loggerConfig.addAppender(appender, null, null);这是正常工作,除了从最大数量的文件...在我的策略中,我得到的文件比前4个文件还多。怎么啦?欢迎任何帮助!
提前谢谢你,
致敬Peter
发布于 2019-02-14 01:20:09
pfff花了我一段时间但我让它工作了.这里没有太多关于编程更改log4j2附加器的信息,所以这是我的解决方案:
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
PathCondition[] pathConditions = new PathCondition[1];
pathConditions[0] = IfAccumulatedFileCount.createFileCountCondition(Integer.parseInt(expire));
DeleteAction action = DeleteAction.createDeleteAction("C:\\logs\\BuddyServer\\", true, 1, false, null, pathConditions, null, config);
Action[] actions = new Action[1];
actions[0] = action;
DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
.withMax(expire)
.withCustomActions(actions)
.withMin("1")
.withFileIndex("max")
.withConfig(config)
.withCompressionLevelStr(Deflater.NO_COMPRESSION + "")
.build();
PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config)
.withPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%5p] %pid --- %-40.40logger{39} : %m%n%wEx")
.build();
RollingFileAppender appender = RollingFileAppender.newBuilder().setConfiguration(config)
.withName("TraceFileAppender")
.withLayout(layout)
.withFileName(file + ".log")
.withFilePattern(file + ".%d{yyyy-MM-ddHHmmSSS}.log")
.withPolicy(SizeBasedTriggeringPolicy.createPolicy(segment))
.withStrategy(strategy)
.build();
appender.start();
config.addAppender(appender);
LoggerConfig loggerConfig = config.getRootLogger();
loggerConfig.setLevel(Level.toLevel(buddyConfig.getOption("log", "verbose").toUpperCase()));
loggerConfig.addAppender(appender, null, null);https://stackoverflow.com/questions/54660355
复制相似问题