- jar包引入:
核心包
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>2.0.2</version>
</dependency>
(slf4j包作为可选条件进入导入,由于部分框架必须引入slfj才能实现日志打印,比如:mongodb)
Slf4j和异步输出包
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>v1.7.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>v1.7.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.0</version>
</dependency>
- 自定义自己的日志输出:
org.apache.logging.log4j.LogManager.getLogger(clazz)
log4j2不再支持properties文件了,只支持xml,json或是yaml,不指定位置的情况下默认在src/main/resources下查找。
如果需要自定义位置,需要在上面的web.xml中添加以下代码
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>/WEB-INF/classes/log4j2.xml</param-value>
</context-param>
- 全异步模式:
注意:在JVM启动参数中增加
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector开启异步日志.
System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
- 混合异步模式 - (在配置文件中使用AsyncLogger 或者 asyncRoot)
<loggers>
<AsyncLogger name="AsyncLogger" level="trace" includeLocation="true">
<appender-refref="Console" />
<appender-refref="debugLog" />
<appender-refref="errorLog" />
</AsyncLogger>
<asyncRoot level="trace" includeLocation="true">
<appender-refref="Console" />
</asyncRoot>
</loggers>