日志系列之Log4j2异步Loggers

性能提升

Log4j2引入异步Loggers,显著提升了日志吞吐量和降低了延时,如下图所示:
日志系列之Log4j2异步Loggers_第1张图片
日志系列之Log4j2异步Loggers_第2张图片

技术原理

  1. 基于Disruptor,实现了线程间通信的无锁化;
  2. 无GC模式:通过对象复用,避免频繁创建对象,减少GC次数;

所有Loggers异步

  1. 添加disruptor包;

Log4j-2.9 and higher require disruptor-3.3.4.jar or higher on the classpath. Prior to Log4j-2.9, disruptor-3.0.0.jar or higher was required.

  1. 设置log4j2.contextSelector系统参数;
-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

配置文件如下图所示:

?xml version="1.0" encoding="UTF-8"?>



<Configuration status="WARN">
  <Appenders>
    
    <RandomAccessFile name="RandomAccessFile" fileName="async.log" immediateFlush="false" append="false">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m %ex%nPattern>
      PatternLayout>
    RandomAccessFile>
  Appenders>
  <Loggers>
    <Root level="info" includeLocation="false">
      <AppenderRef ref="RandomAccessFile"/>
    Root>
  Loggers>
Configuration>

注意:此时使用正常的 和标签,否则会增加不必要的消耗;

When AsyncLoggerContextSelector is used to make all loggers asynchronous, make sure to use normal and elements in the configuration. The AsyncLoggerContextSelector will ensure that all loggers are asynchronous, using a mechanism that is different from what happens when you configure or . The latter elements are intended for mixing async with sync loggers. If you use both mechanisms together you will end up with two background threads, where your application passes the log message to thread A, which passes the message to thread B, which then finally logs the message to disk. This works, but there will be an unnecessary step in the middle.

同步和异步混合Loggers

  1. 添加disruptor包;

详情参考:https://logging.apache.org/log4j/2.x/manual/async.html

你可能感兴趣的:(杂谈)