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");
	}

}

结果:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd29iZW5kaWFua3Vu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" >

时间: 2024-11-20 12:22:28

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.Conversion

一个线程 就是一个 人!!!

一个线程 就是一个 人!!! 这个想法我早已有之..! 参考 若把线程当作一个人,所有问题都瞬间明白了 (38/3432) 原文地址:https://www.cnblogs.com/FlyAway2013/p/11101864.html

python创建一个线程和一个线程池

创建一个线程 1.示例代码 import time import threading def task(arg): time.sleep(2) while True: num = input('>>>') t = threading.Thread(target=task.args=(num,)) t.start() 创建一个线程池 1.示例代码 import time from concurrent.futures import ThreadPoolExecutor def task(m

【转】window 服务器的Tomcat 控制台日志保存到日志文件

    原文链接:https://www.cnblogs.com/Warmsunshine/p/6236076.html 在Linux系统中,Tomcat 启动后默认将很多信息都写入到 catalina.out 文件中,我们可以通过tail  -f  catalina.out 来跟踪Tomcat 和相关应用运行的情况. 在windows下,我们使用startup.bat启动Tomcat以后,会发现catalina日志与Linux记录的内容有很大区别,大多信息只输出到屏幕而没有记录到catalin

C++ RAII手法实现的线程安全的日志文件写例子

#include <iostream> #include <fstream> #include <string> #include <cstdarg> #include <cstdio> #include <pthread.h> // MutexLock 封装互斥锁的接口 class MutexLock { public: MutexLock() { pthread_mutex_init(&mutex_, NULL); } M

PHP保存本地日志文件

*** 写文件* @param    string  $file   文件路径* @param    string  $str    写入内容* @param    char    $mode   写入模式*/function writeFile($file,$str,$mode='w'){    $oldmask = @umask(0);    $fp = @fopen($file,$mode);    @flock($fp, 3);    if(!$fp)    {        Retur

显示日期和时间,列出所有登录的用户,给出系统的更新时间,最后将所有信息保存到日志文件中

#!/bin/bash d1=`date +%F` d2=`date +%T` num=`cat /etc/passwd |awk -F ':' '{print $7}' |sed -n '/bin\/bash/'p |wc -l` echo "$d1  $d2  $num users" >> /root/date.log

log4j配置每天生成一个日志文件

首先需要配置web.xml里面: <servlet-name>log4j-init</servlet-name> <servlet-class>com.free.core.util.Log4j</servlet-class> <init-param> <param-name>log4j</param-name> <param-value>/WEB-INF/classes/logxml/log4j.xml<

java log4j 日志文件

开发中经常会用到log日志文件,根据业务需要可能不产生很大日志文件给维护和[排错带来了麻烦.所以我们希望能够每天或每个月产生一个日志文件,这样文件不至于过大. 或者根据日志文件大小来判断,超过规定大小,日志自动增加新文件. 下面针对log4j中这两种方式的实现都很简单,只要在配置文件中设置即可.实例如下: 第一种方式: log4j.rootLogger = DEBUG,con,FILE log4j.appender.con=org.apache.log4j.ConsoleAppender log