logback指定时间执行压缩

问题:因日志文件太多,导致logbck每天晚上0点压缩占用CPU太高。

解决方案:指定部分log文件在其它时间进行压缩。

思路:重写 computeNextCheck(),设置nextCheck的值为你需要的时间。

logback.xml:

<appender name="kafkaRecordLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter>
<level>TRACE</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.dir}/。。。-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxHistory>7</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="com.。。。.server.utils.MySizeAndTimeBasedFNATP">
<multiple>3</multiple>
<maxFileSize>5GB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<file>${log.dir}/。。。.log</file>
<encoder charset="UTF-8">
<pattern>%msg%n</pattern>
</encoder>
</appender>

java代码:

package com.。。。.server.utils;

import ch.qos.logback.core.joran.spi.NoAutoStart;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;

import java.util.Calendar;

@NoAutoStart
public class MySizeAndTimeBasedFNATP<E> extends SizeAndTimeBasedFNATP<E> {
private Integer multiple = 1;

@Override
protected void computeNextCheck() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, multiple);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
nextCheck = c.getTimeInMillis();
}

public Integer getMultiple() {
return multiple;
}

public void setMultiple(Integer multiple) {
if (multiple > 1) {
this.multiple = multiple;
}
}
}
posted @ 2019-03-11 09:55  会飞的灰机  阅读(3021)  评论(0编辑  收藏  举报