本文概览 :选择打印日志方案为: 使用log4j,并且使用AsyncLogger 异步打印。
1 、项目中选择日志框架是 log4j2 。
因为目前常遇见的日志框架有 log4j 、 logback 、 log4j2 , logback 是为了优化 log4j 而生的, log4j2 又在 logback 基础上做了优化。所以日志框架选型顺序为: log4j2 > logback > log4j 。这三个都是同一个作者所写。
2 、 log4j2 配置为异步方式
使用同步方式,在高并发情况下会对接口性能有影响,所以使用异步方式。异步日志有 AsyncAppender 和 AsyncLogger 两种方式, 建议使用 AsyncLogger 方式 。AsyncLogger是log4j2新增的,使用LMAX Disruptor来实现高吞吐量;Async Appender在log4j1的时候就已经有了。
1 、 maven 配置
<!--配置4j--> <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>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.4.2</version> </dependency>
2、log4j2.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!-- No need to set system property "Log4jContextSelector" to any value
when using <asyncLogger> or <asyncRoot>. -->
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout>
<Pattern>%d %p %class{1.} [%t] %location %m %ex%n</Pattern>
</PatternLayout>
</Console>
<!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
<RandomAccessFile name="RandomAccessFile" fileName="./sync.log"
immediateFlush="false" append="false">
<PatternLayout>
<Pattern>%d %p %class{1.} [%t] %location %m %ex%n</Pattern>
</PatternLayout>
</RandomAccessFile>
</Appenders>
<Loggers>
<!-- pattern layout actually uses location, so we need to include it -->
<AsyncLogger name="com.test" level="info" includeLocation="true">
<AppenderRef ref="RandomAccessFile"/>
<AppenderRef ref="Console"/>
</AsyncLogger>
<AsyncRoot level="info" includeLocation="true">
<AppenderRef ref="RandomAccessFile"/>
</AsyncRoot>
</Loggers>
</Configuration>
一个项目中只能使用log4j2或者logback。假设在项目中使用了log4j2,此时使用外部依赖jar时候,发现外部依赖使用了logbakc,如何解决这个问题? 将外部依赖的logback的包通过exclude排除掉 。
Log4j2中的同步日志与异步日志 https://www.cnblogs.com/yeyang/p/7944906.html
高性能队列——Disruptor https://tech.meituan.com/2016/11/18/disruptor.html
Asynchronous Loggers for Low-Latency Logging https://logging.apache.org/log4j/log4j-2.3/manual/async.html