当前位置: 移动技术网 > IT编程>开发语言>Java > log4j2日志异步打印(实例讲解)

log4j2日志异步打印(实例讲解)

2019年07月19日  | 移动技术网IT编程  | 我要评论

log4j2支持日志的异步打印,日志异步输出的好处在于,使用单独的进程来执行日志打印的功能,可以提高日志执行效率,减少日志功能对正常业务的影响。

异步日志在程序的classpath需要加载disruptor-3.0.0.jar或者更高的版本。

asynchronous loggers是一个新增特性在log4j 2 ,可以实现完全异步也可以和同步混合使用,还可以只异步化appender,以提升系统性能,官方数据显示混合没有完全异步化效果好。

1,完全异步模式:

这种异步日志方式,不需要修改原来的配置文件,logger仍然使用<root> and <logger>

只需要在主程序代码开头,加一句系统属性的代码:

system.setproperty("log4jcontextselector", "org.apache.logging.log4j.core.async.asyncloggercontextselector");

或者设置启动参数:

dlog4jcontextselector=org.apache.logging.log4j.core.async.asyncloggercontextselector

2,异步和非异步混合输出模式

在配置文件中logger使用<asyncroot> 或 <asynclogger>,而且<asyncroot> 或 <asynclogger>可以和<root> 或 <logger>混合使用。

<?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>
<!-- async loggers will auto-flush in batches, so switch off immediateflush. -->
<randomaccessfile name="randomaccessfile" filename="asyncwithlocation.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.foo.bar" level="trace" includelocation="true">
<appenderref ref="randomaccessfile"/>
</asynclogger>
<root level="info" includelocation="true">
<appenderref ref="randomaccessfile"/>
</root>
</loggers>
</configuration>

这里需要注意的是,如果使用<asyncroot> 或 <asynclogger>,includelocation="true"是必须要设置才会有类路径等一些信息打印出来。

3,只异步化appender

在<appenders>标签里增加如下<async>标签

<async name="asyncappender" includelocation="true"> 
<appenderref ref="randomaccessfile"/>
</async>

然后在<root>或者<logger>标签中引用asyncappender即可,这里includelocation是增加在<async>标签中的。

<root level="info">
<appenderref ref="randomaccessfile"/>
</root>

无论是完全异步模式还是混合模式,在appender标签中,immediateflush属性无论为true或者false,效果都是和设置false是一样的。

4,性能对比

完全异步 > 混合模式 > 只异步化appender > 同步

5,疑问

使用混合异步模式进行多线程写日志测试的时候,偶尔会出现日志没有写完的情况。是不是主线程执行完了,不会等待写日志的线程执行完,就把进程给停掉了? 在主线程的最后sleep几秒,就没有再出现日志写不完的情况了。

以上这篇log4j2日志异步打印(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网