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

Posted mfmdaoyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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");
	}
	
}


结果:

技术分享



以上是关于log4j实现每一个线程保存一个日志文件的主要内容,如果未能解决你的问题,请参考以下文章

程序源代码Log4J 日志分割

log4j实现日志的输出

Java项目中如何使用log4j和slf4j实现日志打印

Log4j

日志及log4j框架

Log4j笔记