logback按照文件大小切割日志

在日志的处理方面,logback是一套比较主流的日志框架,SpringBoot默认使用的就是logback。通过配置logback.xml,可以灵活的实现我们对日志的各种格式需求。
在使用中发现1.1.*版本和1.2.*有些区别,前面的版本貌似不支持单纯的按照日志文件大小来切割日志,后面的版本需要配置最大保存时间等参数,以及在格式上需要加随机数%i来实现。此格式与所需的日志格式有点冲突,于是想到了重写。

常见的处理方式是按照时间和大小来分割,并不能单纯按照日志文件大小来分割,若要实现这种分割方式,需要重写SizeAndTimeBasedFNATP类。

1、重写SizeAndTimeBasedFNATP类

package ch.qos.logback.core.rolling;

import ch.qos.logback.core.joran.spi.NoAutoStart;	
import ch.qos.logback.core.rolling.helper.ArchiveRemover;
import ch.qos.logback.core.rolling.helper.CompressionMode;
import ch.qos.logback.core.rolling.helper.FileFilterUtil;
import ch.qos.logback.core.rolling.helper.SizeAndTimeBasedArchiveRemover;
import ch.qos.logback.core.util.DefaultInvocationGate;
import ch.qos.logback.core.util.FileSize;
import ch.qos.logback.core.util.InvocationGate;

import java.io.File;


/**
 * logback的1.2版本之前没有有对按照日志大小切割的支持,1.2.3版本有SizeAndTimeBasedFNATP这个方法
 * 配置与当前重写之后的配相同
 * @author Liu Ke
 * @create 2019/4/12  15:58
 * @desc    实现按照文件大小切割日志,重写logback中方法
*/
@NoAutoStart
public class ReSizeAndTimeBasedFNATP extends 	TimeBasedFileNamingAndTriggeringPolicyBase{

enum Usage {EMBEDDED, DIRECT};


int currentPeriodsCounter = 0;
FileSize maxFileSize;
// String maxFileSizeAsString;

long nextSizeCheck = 0;
static String MISSING_INT_TOKEN = "Missing integer token, that is %i, in FileNamePattern [";
static String MISSING_DATE_TOKEN = "Missing date token, that is %d, in FileNamePattern [";

private final Usage usage;

public ReSizeAndTimeBasedFNATP() {
    this(Usage.DIRECT);
}

public ReSizeAndTimeBasedFNATP(Usage usage) {
    this.usage = usage;
}

@Override
public void start() {
    // we depend on certain fields having been initialized in super class
    super.start();
    //此处判断暂时用不到
    /*if(usage == Usage.DIRECT) {
        addWarn(CoreConstants.SIZE_AND_TIME_BASED_FNATP_IS_DEPRECATED);
        addWarn("For more information see "+MANUAL_URL_PREFIX+"appenders.html#SizeAndTimeBasedRollingPolicy");
    }*/

    if (!super.isErrorFree())
        return;


    if (maxFileSize == null) {
        addError("maxFileSize property is mandatory.");
        withErrors();
    }

    if (!validateDateAndIntegerTokens()) {
        withErrors();
        return;
    }

    archiveRemover = createArchiveRemover();
    archiveRemover.setContext(context);

    // we need to get the correct value of currentPeriodsCounter.
    // usually the value is 0, unless the appender or the application
    // is stopped and restarted within the same period
    String regex = tbrp.fileNamePattern.toRegexForFixedDate(dateInCurrentPeriod);
    String stemRegex = FileFilterUtil.afterLastSlash(regex);

    computeCurrentPeriodsHighestCounterValue(stemRegex);

    if (isErrorFree()) {
        started = true;
    }
}

private boolean validateDateAndIntegerTokens() {
    boolean inError = false;
    //此处判断暂时用不到
    /*if (tbrp.fileNamePattern.getIntegerTokenConverter() == null) {
        inError = true;
        addError(MISSING_INT_TOKEN + tbrp.fileNamePatternStr + "]");
        addError(CoreConstants.SEE_MISSING_INTEGER_TOKEN);
    }*/
    if (tbrp.fileNamePattern.getPrimaryDateTokenConverter() == null) {
        inError = true;
        addError(MISSING_DATE_TOKEN + tbrp.fileNamePatternStr + "]");
    }

    return !inError;
}

protected ArchiveRemover createArchiveRemover() {
    return new SizeAndTimeBasedArchiveRemover(tbrp.fileNamePattern, rc);
}

void computeCurrentPeriodsHighestCounterValue(final String stemRegex) {
    File file = new File(getCurrentPeriodsFileNameWithoutCompressionSuffix());
    File parentDir = file.getParentFile();

    File[] matchingFileArray = FileFilterUtil.filesInFolderMatchingStemRegex(parentDir, stemRegex);

    if (matchingFileArray == null || matchingFileArray.length == 0) {
        currentPeriodsCounter = 0;
        return;
    }
    currentPeriodsCounter = FileFilterUtil.findHighestCounter(matchingFileArray, stemRegex);

    // if parent raw file property is not null, then the next
    // counter is max found counter+1
    if (tbrp.getParentsRawFileProperty() != null || (tbrp.compressionMode != CompressionMode.NONE)) {
        // TODO test me
        currentPeriodsCounter++;
    }
}

InvocationGate invocationGate = new DefaultInvocationGate();

@Override
public boolean isTriggeringEvent(File activeFile, final E event) {

    long time = getCurrentTime();

    // first check for roll-over based on time,不依据时间切割
    /*if (time >= nextCheck) {
        Date dateInElapsedPeriod = dateInCurrentPeriod;
        elapsedPeriodsFileName = tbrp.fileNamePatternWithoutCompSuffix.convertMultipleArguments(dateInElapsedPeriod, currentPeriodsCounter);
        currentPeriodsCounter = 0;
        setDateInCurrentPeriod(time);
        computeNextCheck();
        return true;
    }*/

    // next check for roll-over based on size
    if (invocationGate.isTooSoon(time)) {
        return false;
    }

    if (activeFile == null) {
        addWarn("activeFile == null");
        return false;
    }
    if (maxFileSize == null) {
        addWarn("maxFileSize = null");
        return false;
    }
    if (activeFile.length() >= maxFileSize.getSize()) {

        elapsedPeriodsFileName = tbrp.fileNamePatternWithoutCompSuffix.convertMultipleArguments(dateInCurrentPeriod, currentPeriodsCounter);
        currentPeriodsCounter++;
        return true;
    }

    return false;
}

@Override
public String getCurrentPeriodsFileNameWithoutCompressionSuffix() {
    return tbrp.fileNamePatternWithoutCompSuffix.convertMultipleArguments(dateInCurrentPeriod, currentPeriodsCounter);
}

public void setMaxFileSize(FileSize aMaxFileSize) {
    this.maxFileSize = aMaxFileSize;
}



}

2、配置logback.xml








    
        
        %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
    




    ${LOG_HOME}/${APP_NAME}-${HOSTNAME}.log
    
        ${LOG_HOME}/${APP_NAME}-${HOSTNAME}-%d{MMddHHmmss}.log
        
            10MB
        
    
    
        %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger -%msg%n
        UTF-8
    




    


你可能感兴趣的:(java基础,spring,springcloud)