首页 > 代码库 > log4j实现每个线程保存一个日志文件

log4j实现每个线程保存一个日志文件

log4j.properties:

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%-5p] [%c.%M()]:%c{1}.java %L - %m%n

### direct log messages to myfile ###
log4j.appender.myfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myfile.file = F:/eespace/log-test/logs/mylog.log
log4j.appender.myfile.datePattern='.'yyyy-MM-dd
log4j.appender.myfile.layout=org.apache.log4j.PatternLayout
log4j.appender.myfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%-5p] [%c.%M()]:%c{1}.java %L - %m%n

### direct log myThreadfile to stdout ###
log4j.appender.myThreadfile=com.demo.hello.provider.log_test.ThreadDailyRollingAppenderDecorator
log4j.appender.myThreadfile.maxFileSize=60
log4j.appender.myThreadfile.maxThreadSize=5
log4j.appender.myThreadfile.filePath=F:/eespace/log-test/logs
log4j.appender.myThreadfile.threadLogFileName=thread_log.log
log4j.appender.myThreadfile.datePattern='.'yyyy-MM-dd
log4j.appender.myThreadfile.layout=org.apache.log4j.PatternLayout
log4j.appender.myThreadfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%-5p] [%c.%M()]:%c{1}.java %L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout,myfile
#myThreadfile
log4j.logger.com.demo.hello.provider.log_test=info, stdout,myThreadfile


ThreadDailyRollingAppenderDecorator:

/**
 * @author wumingkun
 * @version 1.0.0
 * @Description
 */

package com.demo.hello.provider.log_test;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Layout;


/**
 * @author wumingkun
 * 
 */
public class ThreadDailyRollingAppenderDecorator extends
		DailyRollingFileAppender implements Cloneable {
	private int maxFileSize;
	private int maxThreadSize;
	private String filePath;
	private String threadLogFileName;
	DailyRollingFileAppender fileAppender;

	public ThreadDailyRollingAppenderDecorator() {
		super();
	}

	public ThreadDailyRollingAppenderDecorator(Layout layout, String filename,
			String datePattern) throws IOException {
		super(layout, filename, datePattern);
	}
	

	public ThreadDailyRollingAppenderDecorator(
			ThreadDailyRollingAppenderDecorator fileAppender,String threadName) throws IOException {
		this(fileAppender.getLayout(),fileAppender.getFileName(threadName),fileAppender.getDatePattern());
		this.fileAppender = fileAppender;
	}

	public DailyRollingFileAppender getFileAppender() {
		return fileAppender;
	}

	public void setFileAppender(DailyRollingFileAppender fileAppender) {
		this.fileAppender = fileAppender;
	}

	public int getMaxFileSize() {
		return maxFileSize;
	}

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

	public Object copy() {
		try {
			return this.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int getMaxThreadSize() {
		return maxThreadSize;
	}

	public void setMaxThreadSize(int maxThreadSize) {
		this.maxThreadSize = maxThreadSize;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getThreadLogFileName() {
		return threadLogFileName;
	}

	public void setThreadLogFileName(String threadLogFileName) {
		this.threadLogFileName = threadLogFileName;
	}

	public void init(String threadName) {
		this.name = threadName;
		this.setFile(getFileName(threadName));
		try {
			this.setFile(this.fileName, true, false, this.bufferSize);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return
	 */
	public  String getFileName(String threadName) {
		return this.filePath + File.separator + threadName + File.separator
				+ this.threadLogFileName;
	}

}


ThreadLoggerFactory:

/**
 * @author wumingkun
 * @version 1.0.0
 * @Description
 */

package com.demo.hello.provider.log_test;

import java.io.IOException;
import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;

/**
 * @author wumingkun
 *
 */
public class ThreadLoggerFactory {
	static  final String prefix="com.demo.hello.provider.log_test";
	static Logger parentLogger ;
	static {
		parentLogger=Logger.getLogger(prefix);
	}
	public  static Logger getLogger(){
		Logger logger =Logger.getLogger(prefix+Thread.currentThread().getName());
		addAppender(logger,Thread.currentThread().getName());
		return logger;
	}
	/**
	 * @param name
	 */
	private static void addAppender(Logger logger,String threadName) {
		Enumeration<Appender> appends=parentLogger.getAllAppenders();
		if(!logger.getAllAppenders().hasMoreElements()){
			while (appends.hasMoreElements()) {
				Appender appender = (Appender) appends.nextElement();
				if(appender instanceof ThreadDailyRollingAppenderDecorator){
					ThreadDailyRollingAppenderDecorator myappender=(ThreadDailyRollingAppenderDecorator)appender;
					try {
						logger.addAppender(new ThreadDailyRollingAppenderDecorator(myappender,threadName));
					} catch (IOException e) {
						e.printStackTrace();
					}
					continue;
				}
				logger.addAppender(appender);
			}
		}
		
	}
}


ThreadLogTest:

/**
 * 
 * @author wumingkun
 * @version 1.0.0
 * @Description
 */

package com.demo.hello.provider.log_test;

import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;

/**
 * @author wumingkun
 *
 */
public class ThreadLogTest {
	static Logger logger=Logger.getLogger(ThreadLogTest.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MyThread myThread=new MyThread();
		for(int i=1;i<11;i++){
			new Thread(myThread, "mythread"+i).start();
		}
	}

}
class MyThread implements Runnable{
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
			Logger logger=ThreadLoggerFactory.getLogger();
			logger.debug(Thread.currentThread().getName()+" -----debug");
			logger.info(Thread.currentThread().getName()+" -----info");
	}
	
}


结果: