import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender; import org.apache.logging.log4j.core.config.*; import org.apache.logging.log4j.core.layout.PatternLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy; import org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy; import org.apache.logging.log4j.core.appender.rolling.OnStartupTriggeringPolicy; import org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy; import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
private static Logger getRollingFileAppender(String logName) { //日志路径 String logPath = System.getProperty("webapp.root") + "/../data/log";
try { //获取当前配置 LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration configuration = loggerContext.getConfiguration();
// 创建RollingFileAppender AbstractAppender.Builder appender2 = RollingRandomAccessFileAppender.newBuilder() .withFileName(logPath + "/" + logName + ".log") .withFilePattern(logPath + "/" + logName + "-%d{yyyy-MM-dd}.log") .withAppend(true) .withPolicy(createTriggeringPolicy()) .withStrategy(DefaultRolloverStrategy.newBuilder().withFileIndex("max").withConfig(configuration).build()) .withImmediateFlush(false) .withLayout(PatternLayout.newBuilder().withPattern("[%d{yyyy-MM-dd HH:mm:ss}][%p][%c][%x][%m]%n").build()) .withName(logName);
//启动appender RollingRandomAccessFileAppender appender = ((RollingRandomAccessFileAppender.Builder) appender2).build(); appender.start(); configuration.addAppender(appender);
//创建Logger AppenderRef ref = AppenderRef.createAppenderRef(logName + "Appender", null, null); LoggerConfig loggerConfig = LoggerConfig.createLogger(false, org.apache.logging.log4j.Level.INFO, logName, "false", new AppenderRef[]{ref}, null, configuration, null); loggerConfig.addAppender(appender, null, null); configuration.addLogger(logName, loggerConfig);
//更新配置 loggerContext.updateLoggers(configuration);
//返回Logger return LoggerFactory.getLogger(logName); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 日志策略. * * @return */ private static CompositeTriggeringPolicy createTriggeringPolicy() { TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.newBuilder() .withInterval(10) .withModulate(true) .build(); OnStartupTriggeringPolicy onStartupTriggeringPolicy = OnStartupTriggeringPolicy.createPolicy(1); SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy("100MB");
return CompositeTriggeringPolicy.createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy, onStartupTriggeringPolicy); }
|