log4j2 异步多线程打印日志

log4j2 异步多线程打印日志

Maven依赖

<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-1.2-api</artifactId>
	<version>2.3</version>
</dependency>
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-api</artifactId>
	<version>2.3</version>
</dependency>
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-core</artifactId>
	<version>2.3</version>
</dependency>
<dependency>
	<groupId>com.lmax</groupId>
	<artifactId>disruptor</artifactId>
	<version>3.3.4</version>
</dependency>

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn"
packages="com.hoperun.zhulongxiang.asnc_print_different_logfile">
<Appenders>
    <console name="console" target="system_out">
		<!-- 只输出level及以上级别的信息(onmatch),其他的直接拒绝(onmismatch)。默认就是trace。      
		<thresholdfilter 
			level="trace" onmatch="accept" onmismatch="deny"/> -->
		<patternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} -
		%m%n" />
	</console>
	<Routing name="Routing">
		<Routes pattern="$${thread:threadName}">
			<Route>
				<RollingFile name="logFile-${thread:threadName}"
					fileName="log/${thread:threadName}.log"
					filePattern="log/${thread:threadName}-%d{MM-dd-yyyy}-%i.log">
					<PatternLayout pattern="%d %-5p [%t] %C{2} - %m%n" />
					<Policies>
						<SizeBasedTriggeringPolicy size="50 MB" />
					</Policies>
					<DefaultRolloverStrategy max="100" />
				</RollingFile>
			</Route>
		</Routes>
	</Routing>
	<Async name="async" bufferSize="1000" includeLocation="true">
		<AppenderRef ref="Routing" />
		<AppenderRef ref="console" />
	</Async>
</Appenders>
<Loggers>
	<Root level="debug">
		<AppenderRef ref="async" />
	</Root>
</Loggers>
</Configuration>

核心java类

package com.hoperun.zhulongxiang.asnc_print_different_logfile;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;

@Plugin(name = "thread", category = StrLookup.CATEGORY)
public class ThreadLookup implements StrLookup {

	public String lookup(String key) {
		return Thread.currentThread().getName();
	}

	public String lookup(LogEvent event, String key) {
		return event.getThreadName() == null ? Thread.currentThread().getName() : event.getThreadName();
	}

}

这里@Plugin中的name的值对应log4j2.xml中<Routes pattern="$${thread:threadName}">配置中的thread

准备两个线程类

package com.hoperun.zhulongxiang.asnc_print_different_logfile;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LogThread implements Runnable {

	private static final Logger LOGGER = LogManager.getLogger(LogThread.class);

	public String threadName;

	public LogThread(String threadName) {
		this.threadName = threadName;
	}

	public void run() {
		Thread.currentThread().setName(threadName);
		LOGGER.info("1");
	}

}


package com.hoperun.zhulongxiang.asnc_print_different_logfile;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class OtherLogThread implements Runnable {

	private static final Logger LOGGER = LogManager.getLogger(LogThread.class);

	public String threadName;

	public OtherLogThread(String threadName) {
		this.threadName = threadName;
	}

	public void run() {
		Thread.currentThread().setName(threadName);
		LOGGER.info("2");
	}

}

测试

package com.hoperun.zhulongxiang.asnc_print_different_logfile;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.nutz.ioc.Ioc;

import com.hoperun.base.IocMaster;

public class LogApp {

	static {
		System.setProperty("log4j.configurationFile", "etc/log4j2.xml");
	}

	private static final Logger LOGGER = LogManager.getLogger(LogApp.class);

	public static void main(String[] args) {
		ThreadContext.put("threadName", Thread.currentThread().getName());
		LogThread t1 = new LogThread("123123123");
		OtherLogThread t2 = new OtherLogThread("4564564564");
		ExecutorService pool = Executors.newFixedThreadPool(20);
		pool.submit(t1);
		pool.submit(t2);
		
	}
}

这里ThreadContext.put("threadName", Thread.currentThread().getName())设置的参数threadName对应log4j2.xml中<Routes pattern="$${thread:threadName}">配置中的threadName

日志

09:44:39.704 [123123123] INFO  com.hoperun.zhulongxiang.asnc_print_different_logfile.LogThread -    1
09:44:39.704 [4564564564] INFO  com.hoperun.zhulongxiang.asnc_print_different_logfile.LogThread -    2

日志中的线程名已经修改成我们设定的名称。log下已经有了我们想要的以线程名命名的日志文件了。
posted on 2020-01-10 11:33  createwell  阅读(3615)  评论(0编辑  收藏  举报