在日志的处理方面,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<E> extends TimeBasedFileNamingAndTriggeringPolicyBase<E>{
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
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="/IDEA/Spring/apple/logs" />
<property name="APP_NAME" value="apple"/>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!--日志文件按照指定大小切割,需要重写jar包中的类-->
<appender name="CUT_BY_SIZE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_HOME}/${APP_NAME}-${HOSTNAME}.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${LOG_HOME}/${APP_NAME}-${HOSTNAME}-%d{MMddHHmmss}.log</FileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.ReSizeAndTimeBasedFNATP">
<MaxFileSize>10MB</MaxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger -%msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="CUT_BY_SIZE" />
</root>
</configuration>