简体   繁体   中英

Log4j2 auto rollover scheduler

How can I configure log4j2 for rollover every 30 seconds?

For example, if today is 2019-01-09 09:45:00 and I write data into the log file by command

log.info("test")

no more data goes to log for the 10 minutes, but I need auto rollover log file after 30 seconds in 2019-01-09 09:45:30.

If I configure log4j2 that's way:

<RollingFile name="RollingFile">
  <FileName>C:/log/mylog.log</FileName>
  <FilePattern>C:/log/time-based-logs/%d{yyyy-MM-dd-hh-mm}.log.zip</FilePattern>
  <PatternLayout>
    <Pattern>%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
  </PatternLayout>
  <Policies>
    <TimeBasedTriggeringPolicy interval="2" modulate="true" />
  </Policies>
  <DefaultRolloverStrategy max="5" />
</RollingFile>

I must write into log data by the command

log.info("test1")      // 2019-01-09 09:55:00

and then goes rollover file after 10 minutes, but I need every 30 seconds even no write data into log anymore.

How can I do it?

and I apologize for my bad English.

Use RollingFileAppender https://logback.qos.ch/manual/appenders.html#RollingFileAppender

And TimeBasedRollingPolicy https://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy

But that allows you to fine grain to minute (and every second, but not to 30 sec period).

If that is not enough for you, write your own custom RollingPolicy https://logback.qos.ch/apidocs/ch/qos/logback/core/rolling/RollingPolicy.html

Or just extend TimeBasedRollingPolicy to include additional functionality https://logback.qos.ch/apidocs/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.html

This option came up for me

public class Utils {
public static void rollover(LoggerContext loggerContext) {
    Map<String, Appender> appendersByName = loggerContext.getConfiguration().getAppenders();

    appendersByName.values().forEach(appender -> {
        if (appender instanceof RollingFileAppender) {
            ((RollingFileAppender) appender).getManager().checkRollover(new RolloverLogEvent());
        }
    });
}
}

@Plugin(name = "OnTriggeringPolicy", category = "Core", printObject = true)
public class OnCustomTriggeringPolicy implements TriggeringPolicy {

private RollingFileManager manager;

@PluginFactory
public static OnRolloverEventEventTriggeringPolicy createPolicy() {
    return new OnRolloverPolicy();
}

@Override
public void initialize(RollingFileManager manager) {
    this.manager = manager;
}

@Override
public boolean isTriggeringEvent(LogEvent logEvent) {

    return manager.getFileSize() > 0;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM