如何启用logback以每x分钟/ 5分钟/ 30分钟循环日志文件?

时间:2018-06-19 11:56:02

标签: java logback slf4j logback-classic

我知道logback.xml可以轻松地每天,每小时或每周轮换日志。 如何在fileNamePattern中配置时间戳,以便每半小时或'x'分钟轮换一次日志?

还是这里需要进行代码级更改? 如果是这种情况,那么对于高性能业务级应用程序,它是否线程安全且高效?

2 个答案:

答案 0 :(得分:1)

您不需要更改代码。更改配置文件(logback.xml)就足够了。将追加程序的配置更改为类似于

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logFile.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- daily rollover -->
      <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
      <!-- keep 30 days' worth of history capped at 3GB total size -->
      <maxHistory>30</maxHistory>
      <totalSizeCap>3GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender> 

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>

有关更多详细信息,请参见https://logback.qos.ch/manual/appenders.html。例如使用     logFile。%d {yyyy-MM-dd_HH-mm} .log
在每分钟开始时进行翻转。

答案 1 :(得分:0)

我这样创建了TriggeringPolicy和RollingPolicy:

$n = DB::select('select top 1 id form tags order by id DESC')->first();

$id = $n->id;
class MyTriggeringPolicy<E> extends DefaultTimeBasedFileNamingAndTriggeringPolicy<E> {
  protected int periodMinutes = 1;

  public int getPeriodMinutes() {
    return this.periodMinutes;
  }

  public void setPeriodMinutes(int minutes) {
    if (minutes > 0) {
      this.periodMinutes = minutes;
    }
  }

  private long roundTimestamp(long time) = {
    int periodTicks = periodMinutes * 60000;
    return periodTicks * (time / periodTicks);
  }

  @Override
  public void setDateInCurrentPeriod(long now) {
    dateInCurrentPeriod.setTime(roundTimestamp(now));
  }

  @Override
  public void setDateInCurrentPeriod(Date _dateInCurrentPeriod) {
    dateInCurrentPeriod = new Date(roundTimestamp(_dateInCurrentPeriod.getTime()));
  }

  @Override
  public void computeNextCheck() {
    rc.setTime(dateInCurrentPeriod);
    rc.set(Calendar.SECOND, 0);
    rc.set(Calendar.MILLISECOND, 0);
    rc.add(Calendar.MINUTE, periodMinutes);

    nextCheck = rc.getTime().getTime();
  }

  @Override
  public String toString() {
    return "MyTriggeringPolicy";
  }
}
class MyRollingPolicy<E> extends TimeBasedRollingPolicy<E> {
  private int periodMinutes;

  public int getPeriodMinutes() {
    return this.periodMinutes;
  }

  public void setPeriodMinutes(int minutes) {
    this.periodMinutes = minutes;
  }

  @Override
  public void start() {
    MyTriggeringPolicy<E> triggeringPolicy = new MyTriggeringPolicy<E>();
    triggeringPolicy.setPeriodMinutes(periodMinutes);
    setTimeBasedFileNamingAndTriggeringPolicy(triggeringPolicy);

    super.start();
  }

  @Override
  public String toString() {
    return "MyRollingPolicy";
  }
}

这是在5,10,15 ...分钟内完成的转换。

例如'application-201910301100.log'包含从2019-10-30 11:00:00到2019-10-30 11:04:59的日志。