在開發中,有這樣一種需求:
1. 日志每10分鍾生成一個文件
2. 當前所有的日志文件都歸檔到以今天日期為目錄的文件夾中
那么在logback.xml中該如何配置呢?
在這個https://www.cnblogs.com/wgslucky/p/10026322.html日志中,已經實現了每隔10分鍾生成一個文件的配置,現在需要添加把這些生成的文件按當前日期進行歸檔。
修改配置如下:
<appender name="SYSTEM" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.home}/system.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover ,每10分鍾生成一份日志文件--> <fileNamePattern>${log.home}/%d{yyyy-MM-dd,aux}/system.%d{yyyy-MM-dd-HH-mm}.log </fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="com.common.log.MyTimeBasedFileNamingAndTriggeringPolicy"> <multiple>10</multiple> </timeBasedFileNamingAndTriggeringPolicy> <maxHistory>7</maxHistory> </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss} %-5level [%thread][%file:%line] : %msg%n </pattern> </encoder> </appender>
在fileNamePattern的配置中添加一個日期目錄:%d{yyyy-MM-dd,aux},最主要的是添加了aux標記,logback文檔的原文是這樣說明的:
Multiple %d specifiers It is possible to specify multiple %d specifiers but only one of which can be primary, i.e. used to infer the rollover period. All other tokens must be marked as auxiliary by passing the 'aux' parameter (see examples below). Multiple %d specifiers allow you to organize archive files in a folder structure different than that of the roll-over period. For example, the file name pattern shown below organizes log folders by year and month but roll-over log files every day at midnight. /var/log/%d{yyyy/MM, aux}/myapplication.%d{yyyy-MM-dd}.log
它的意思是說,可以在fileNamePattern配置中添加多個%d的日期符號,但是只能有一個是主要的,其它的只能做為輔助(auxiliary)。在RollingCalendar類中,日志的文件滾動方式就是根據主%d那個日期判斷的。如下面代碼所示:
public RollingCalendar(String datePattern) { super(); this.datePattern = datePattern; this.periodicityType = computePeriodicityType(); } public PeriodicityType computePeriodicityType() { GregorianCalendar calendar = new GregorianCalendar(GMT_TIMEZONE, Locale.getDefault()); // set sate to 1970-01-01 00:00:00 GMT Date epoch = new Date(0); if (datePattern != null) { for (PeriodicityType i : PeriodicityType.VALID_ORDERED_LIST) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern); simpleDateFormat.setTimeZone(GMT_TIMEZONE); // all date formatting done in GMT String r0 = simpleDateFormat.format(epoch); Date next = innerGetEndOfThisPeriod(calendar, i, epoch); String r1 = simpleDateFormat.format(next); // System.out.println("Type = "+i+", r0 = "+r0+", r1 = "+r1); if ((r0 != null) && (r1 != null) && !r0.equals(r1)) { return i; } } } // we failed return PeriodicityType.ERRONEOUS; }