Java 日志 Log4j2

环境

jdk:1.7.0_79
cpu:i5-4570@3.20GHz 4核
eclipse:3.7
操作系统:win7

准备

1.log4j:1.7.21

  1. <dependency>
  2. <groupId>org.slf4j</groupId>
  3. <artifactId>slf4j-log4j12</artifactId>
  4. <version>1.7.21</version>
  5. </dependency>

log4j.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  3. <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
  4. <appender name="myConsole" class="org.apache.log4j.ConsoleAppender">
  5. <layout class="org.apache.log4j.PatternLayout">
  6. <param name="ConversionPattern" value="[%d{dd HH:mm:ss,SSS\} %-5p] [%t] %c{2\} - %m%n" />
  7. </layout>
  8. <!--过滤器设置输出的级别 -->
  9. <filter class="org.apache.log4j.varia.LevelRangeFilter">
  10. <param name="levelMin" value="debug" />
  11. <param name="levelMax" value="warn" />
  12. <param name="AcceptOnMatch" value="true" />
  13. </filter>
  14. </appender>
  15. <appender name="myFile" class="org.apache.log4j.DailyRollingFileAppender">
  16. <param name="File" value="log4jTest.log" />
  17. <param name="Append" value="true" />
  18. <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />
  19. <layout class="org.apache.log4j.PatternLayout">
  20. <param name="ConversionPattern" value="[%t] - %m%n" />
  21. </layout>
  22. </appender>
  23. <appender name="async_file" class="org.apache.log4j.AsyncAppender">
  24. <param name="BufferSize" value="32" />
  25. <appender-ref ref="myFile" />
  26. </appender>
  27. <logger name="org.logTest" additivity="false">
  28. <level value="info" />
  29. <appender-ref ref="async_file" /> <!-- 同步:FILE 异步:async_file -->
  30. </logger>
  31. </log4j:configuration>

2.logback:1.1.7

  1. <dependency>
  2. <groupId>ch.qos.logback</groupId>
  3. <artifactId>logback-classic</artifactId>
  4. <version>1.1.7</version>
  5. </dependency>

logback.xml

  1. <configuration>
  2. <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  3. <!-- encoder 默认配置为PatternLayoutEncoder -->
  4. <encoder>
  5. <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
  6. </pattern>
  7. </encoder>
  8. </appender>
  9. <appender name="FILE" class="ch.qos.logback.core.FileAppender">
  10. <file>testFile.log</file>
  11. <append>true</append>
  12. <encoder>
  13. <pattern>[%t] - %m%n
  14. </pattern>
  15. </encoder>
  16. </appender>
  17. <!-- 异步输出 -->
  18. <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
  19. <discardingThreshold>0</discardingThreshold>
  20. <appender-ref ref="FILE" />
  21. </appender>
  22. <logger name="org.logTest" level="INFO"
  23. additivity="false">
  24. <appender-ref ref="ASYNC" /> <!-- 同步:FILE 异步:ASYNC-->
  25. </logger>
  26. <root level="ERROR">
  27. <appender-ref ref="STDOUT" />
  28. </root>
  29. </configuration>

3.log4j2:2.6.2

  1. <dependency>
  2. <groupId>org.apache.logging.log4j</groupId>
  3. <artifactId>log4j-core</artifactId>
  4. <version>2.6.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.logging.log4j</groupId>
  8. <artifactId>log4j-slf4j-impl</artifactId>
  9. <version>2.6.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.lmax</groupId>
  13. <artifactId>disruptor</artifactId>
  14. <version>3.3.4</version>
  15. </dependency>

log4j2.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--设置log4j2的自身log级别为warn -->
  3. <configuration status="warn">
  4. <appenders>
  5. <console name="Console" target="SYSTEM_OUT">
  6. <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n" />
  7. </console>
  8. <RollingFile name="RollingFileInfo" fileName="info.log"
  9. filePattern="${sys:user.home}/logs/hpaasvc/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
  10. <Filters>
  11. <ThresholdFilter level="INFO" />
  12. <ThresholdFilter level="WARN" onMatch="DENY"
  13. onMismatch="NEUTRAL" />
  14. </Filters>
  15. <PatternLayout pattern="[%t] - %m%n" />
  16. <Policies>
  17. <TimeBasedTriggeringPolicy />
  18. <SizeBasedTriggeringPolicy size="100 MB" />
  19. </Policies>
  20. </RollingFile>
  21. <RandomAccessFile name="RandomAccessFile" fileName="asyncWithLocation.log"
  22. immediateFlush="false" append="true">
  23. <PatternLayout>
  24. <Pattern>[%t] - %m%n</Pattern>
  25. </PatternLayout>
  26. </RandomAccessFile>
  27. </appenders>
  28. <loggers>
  29. <!-- <AsyncLogger name="asynLogger" level="trace"
  30. includeLocation="true">
  31. <AppenderRef ref="RandomAccessFile" />
  32. </AsyncLogger> -->
  33. <Root level="info" includeLocation="true">
  34. <AppenderRef ref="RollingFileInfo" />
  35. </Root>
  36. </loggers>
  37. </configuration>

测试

准备50条线程同时记录1000000条数据,然后统计时间,详细代码如下:

  1. import java.util.concurrent.CountDownLatch;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. public class App {
  5. private static Logger log = LoggerFactory.getLogger(App.class);
  6. public static void main(String[] args) throws InterruptedException {
  7. int messageSize = 1000000;
  8. int threadSize = 50;
  9. final int everySize = messageSize / threadSize;
  10. final CountDownLatch cdl = new CountDownLatch(threadSize);
  11. long startTime = System.currentTimeMillis();
  12. for (int ts = 0; ts < threadSize; ts++) {
  13. new Thread(new Runnable() {
  14. @Override
  15. public void run() {
  16. for (int es = 0; es < everySize; es++) {
  17. log.info("======info");
  18. }
  19. cdl.countDown();
  20. }
  21. }).start();
  22. }
  23. cdl.await();
  24. long endTime = System.currentTimeMillis();
  25. System.out.println("log4j1:messageSize = " + messageSize
  26. + ",threadSize = " + threadSize + ",costTime = "
  27. + (endTime - startTime) + "ms");
  28. }
  29. }

log4j1和logback的同步和异步分别修改为对应的appender就行了
log4j2的异步方式提供了2中模式:

1.全局开启

设置Log4jContextSelector系统属性为:

  1. org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
  2. System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");

2.混合同步异步模式

不需要设置Log4jContextSelector,但是需要使用AsyncLogger标签
更多详细参考官方文档:http://logging.apache.org/log4j/2.x/manual/async.html#AllAsync
结果
分别测试完以后统计成表格如下:
2021-09-09-16-40-35-815318.png
log4j2的异步模式表现了绝对的性能优势,优势主要得益于Disruptor框架的使用

LMAX Disruptor technology. Asynchronous Loggers internally use the Disruptor, a lock-free inter-thread communication library, instead of queues, resulting in higher throughput and lower latency.

一个无锁的线程间通信库代替了原来的队列。