“Log4j 2 异步日志”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第28行: | 第28行: | ||
=== AsyncAppender 方式 === | === AsyncAppender 方式 === | ||
+ | |||
+ | ==== log4j2.xml ==== | ||
+ | <syntaxhighlight lang="xml"> | ||
+ | <?xml version="1.0" encoding="UTF-8"?> | ||
+ | <Configuration status="warn"> | ||
+ | <properties> | ||
+ | <property name="LOG_NAME">E:/logs</property> | ||
+ | </properties> | ||
+ | |||
+ | |||
+ | <Appenders> | ||
+ | <File name="file" fileName="${LOG_HOME}/myfile.log"> | ||
+ | <PatternLayout> | ||
+ | <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> | ||
+ | </PatternLayout> | ||
+ | </File> | ||
+ | |||
+ | <Async name="async"> | ||
+ | <AppenderRef ref="file"/> | ||
+ | </Async> | ||
+ | </Appenders> | ||
+ | |||
+ | <Loggers> | ||
+ | <Root level="error"> | ||
+ | <AppenderRef ref="async" /> | ||
+ | </Root> | ||
+ | </Loggers> | ||
+ | |||
+ | </Configuration> | ||
+ | </syntaxhighlight>这种方式性能上和 Logback 相差无几,所以更推荐下面 AsyncLogger 的方式 |
2023年2月28日 (二) 04:51的版本
https://www.bilibili.com/video/BV1iJ411H74S?p=34
Log4j 2 最大的特点就是异步日志,其性能的提升主要也是从异步日志中受益
Log4j 2 同步日志流程
Log4j 2 异步日志流程
Log4j 2 提供了两种实现日志的方式,一个是通过 AsyncAppender,一个是通过 AsyncLogger,分别对应前面的 Appender 组件和 Logger 组件
实际一般使用 AsyncLogger,因为性能比 AsyncAppender 高很多:https://logging.apache.org/log4j/2.x/performance.html#logging-library-performance-comparison
注意:配置异步日志需要添加依赖
<!-- 异步日志依赖 -->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.4</version>
</dependency>
AsyncAppender 方式
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<properties>
<property name="LOG_NAME">E:/logs</property>
</properties>
<Appenders>
<File name="file" fileName="${LOG_HOME}/myfile.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
<Async name="async">
<AppenderRef ref="file"/>
</Async>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="async" />
</Root>
</Loggers>
</Configuration>
这种方式性能上和 Logback 相差无几,所以更推荐下面 AsyncLogger 的方式