log4j DailyRollingFileAppender不支持只保留最近n天的数据,时间一久导致日志文件很多,并且一天的文件有可能比较大,所以自己写了个appender,以解决这两个问题。
具体代码实现如下:
package com.mytools.common.log4jext;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;
/**
* log4j appender扩展<br>
* (1)按天并且只保留最近n天的 <br>
* (2)如果一天的文件过大,可以按配置的大小将一天的文件进行切分
*
* @author shaoqz
* @since 2016-6-13
*/
public class MyDailyRollingFileAppender extends FileAppender
{
// The code assumes that the following constants are in a increasing
// sequence.
static final int TOP_OF_TROUBLE = -1;
static final int TOP_OF_MINUTE = 0;
static final int TOP_OF_HOUR = 1;
static final int HALF_DAY = 2;
static final int TOP_OF_DAY = 3;
static final int TOP_OF_WEEK = 4;
static final int TOP_OF_MONTH = 5;
/**
* The gmtTimeZone is used only in computeCheckPeriod() method.
*/
public static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
/**
* The default maximum file size is 10MB. , 10K for test
*/
protected long maxFileSize = 10 * 1024;
/**
* The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily
* rollover.
*/
private String datePattern = "'.'yyyy-MM-dd";
/**
* There is one backup file by default.
*/
private int maxBackupIndex = 1;
/**
* The log file will be renamed to the value of the scheduledFilename variable when
* the next interval is entered. For example, if the rollover period is one hour, the
* log file will be renamed to the value of "scheduledFilename" at the beginning of
* the next hour. The precise time when a rollover occurs depends on logging activity.
*/
private String scheduledFilename;
/**
* The next time we estimate a rollover should occur.
*/
private long nextCheck = System.currentTimeMillis() - 1;
private Date now = new Date();
private SimpleDateFormat sdf;
private MyRollingCalendar rollingCalendar = new MyRollingCalendar();
public int checkPeriod = TOP_OF_TROUBLE;
/**
* The default constructor does nothing.
*/
public MyDailyRollingFileAppender()
{
}
/**
* Instantiate a <code>DailyRollingFileAppender</code> and ope