1. maven项目添加依赖
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
![](https://i-blog.csdnimg.cn/blog_migrate/5007380beccb00e371708392e988f9da.png)
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
![](https://i-blog.csdnimg.cn/blog_migrate/468385c858bf8486f7e23685122dc4c7.png)
Substituting Parameters
Frequently the purpose of logging is to provide information about what is happening in the system, which requires including information about the objects being manipulated. In Log4j 1.x this could be accomplished by doing:
- if (logger.isDebugEnabled()) {
- logger.debug("Logging in user " + user.getName() + " with birthday " + user.getBirthdayCalendar()); //这种写法类似于system.out
- }
Doing this repeatedly has the effect of making the code feel like it is more about logging than the actual task at hand. In addition, it results in the logging level being checked twice; once on the call to isDebugEnabled and once on the debug method. A better alternative would be:
logger.debug("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar()); //官方介绍推荐使用这种写法
With the code above the logging level will only be checked once and the String construction will only occur when debug logging is enabled.