随笔 - 107  文章 - 0  评论 - 12  阅读 - 92623

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   createwell  阅读(3626)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 上周热点回顾(1.20-1.26)
· 【译】.NET 升级助手现在支持升级到集中式包管理
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示