Log4j 重写 RollingFileAppender 实现按日期生成文件夹文件名

 

Log4j 不支持按日期生成不同的文件夹

 

通过重写 RollingFileAppender  的 rollOver 、 genFileName 、 subAppend 、 setFile 方法,实现我们的需求(每日生成不同的文件夹,*/2017103021/*.log),日志文件格式 pg_20171030_01.log .

 

/**  
 * Copyright ©2017 DarkFOX. All rights reserved.
 *
 * @Title: Log4JRollingFileAppender.java
 * @Prject: PGFAST
 * @Package: com.pg.core.log4j
 * @Description: TODO
 * @author: ETFox
 * @date: 2017年10月30日 下午2:37:17
 * @version: V1.0
 */
package com.etfox.demofactory;

import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * @ClassName: Log4JRollingFileAppender
 * @Description: TODO 重写 log4j RollingFileAppender,实现文件输出自定义名称
 * @author: ETFox
 * @date: 2017年10月30日 下午2:37:17
 */
public class Log4jRollingFileAppender extends RollingFileAppender {

	private long nextRollover = 0;
	
	private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
	
	public void rollOver() {
		File target;
		File file;
		
		if (qw != null) {
			long size = ((CountingQuietWriter) qw).getCount();
			nextRollover = size + maxFileSize;
		}
		LogLog.debug("maxBackupIndex=" + maxBackupIndex);

		boolean renameSucceeded = true;
		if (maxBackupIndex > 0) {
			// 删除序号最大(最早的文件)的文件
			/*file = new File(genFileName(fileName, maxBackupIndex));
			if (file.exists())
				renameSucceeded = file.delete();*/
			
			// 所有文件名序号加1
			for (int i = maxBackupIndex - 1; i >= 1 && renameSucceeded; i--) {
				file = new File(genFileName(fileName, i));
				if (file.exists()) {
					target = new File(genFileName(fileName, i + 1));
					renameSucceeded = file.renameTo(target);
				}
			}

			if (renameSucceeded) {
				target = new File(genFileName(fileName, 1));

				this.closeFile();

				file = new File(fileName);
				renameSucceeded = file.renameTo(target);

				if (!renameSucceeded) {
					try {
						this.setFile(fileName, true, bufferedIO, bufferSize);
					} catch (IOException e) {
						if (e instanceof InterruptedIOException) {
							Thread.currentThread().interrupt();
						}
						LogLog.error("setFile(" + fileName
								+ ", true) call failed.", e);
					}
				}
			}
		}
		if (renameSucceeded) {
			try {
				this.setFile(fileName, false, bufferedIO, bufferSize);
				nextRollover = 0;
			} catch (IOException e) {
				if (e instanceof InterruptedIOException) {
					Thread.currentThread().interrupt();
				}
				LogLog.error("setFile(" + fileName + ", false) call failed.", e);
			}
		}
	}

	private String genFileName(String name, int index) {
		String val = "_"+df.format(new Date())+"_";
		String fileName = "";
		if (index > 0) {
			String num = index < 10 ? "0" + index : String.valueOf(index);
			fileName = name.replace(".log", "") + val + num + ".log";
		} else {
			fileName = name;
		}
		return fileName;
	}

	protected void subAppend(LoggingEvent event) {
		super.subAppend(event);
		boolean flag = false;
		String[] _files = fileName.split("/");
		int len = _files.length;
        String file_name = _files[len-2];
        String new_file_name = df.format(new Date());
        if(!file_name.equals(new_file_name)){
            flag = true;
            fileName = fileName.replace(file_name, new_file_name);
        }
		if (fileName != null && qw != null) {
			long size = ((CountingQuietWriter) qw).getCount();
			if(flag){
			    size = 0L;
			}
			if ((size >= maxFileSize && size >= nextRollover) || flag) {
				rollOver();
			}
		}
	}
	
	public void setFile(String file) {
	    // Trim spaces from both ends. The users probably does not want
	    // trailing spaces in file names.
	    String val = file.trim();
	    fileName = val.substring(0, val.lastIndexOf("/"))+"/"+df.format(new Date())+
	    		val.substring(val.lastIndexOf("/"), val.length());
	}
	
}

 

 

log4j.properties 代码块:

 

#log4j.rootCategory=debug,CONSOLE,D,I,W,E
log4j.rootCategory=debug,CONSOLE,logFile
########################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.encoding=UTF-8
log4j.appender.CONSOLE.layout.ConversionPattern=$PGFAST>[%d{MM-dd HH:mm:ss}][%-5p] %l >>>> <%m>%n
########################################################################
log4j.appender.logFile=com.etfox.demofactory.Log4jRollingFileAppender
log4j.appender.logFile.encoding=UTF-8
log4j.appender.logFile.File=${catalina.home}/logs/pg.log
log4j.appender.logFile.MaxFileSize=1KB
log4j.appender.logFile.MaxBackupIndex = 10
log4j.appender.logFile.Append = true
#log4j.appender.logFile.DatePattern='_'yyyyMMdd:HHmm:SSS'.log'
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=$PGFAST>[%d][%-5p] %l >>>> %m%n

 

 

 

 

 

你可能感兴趣的:(log)