1. 官网下载log4j
下载的文件
:apache-log4j-2.11.0-bin.zip
![](https://i-blog.csdnimg.cn/blog_migrate/8c9fb7254209491659e3b2091d21e062.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a492e0f1bfd7c80131ca7bbea8ca6918.png)
2. 解压apache-log4j-2.11.0-bin.zip
得到log4j-api-2.11.0.jar和log4j-core-2.11.0.jar;
3. Eclipse新建java project,工程名为LoggerExample
4. 使用 Add External JARs 选项,添加log4j-api-2.11.0.jar和log4j-core-2.11.0.jar;
5. src目录下新建类MyLogger,代码如下:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyLogger {
private static final Logger logger = LogManager.getLogger(MyLogger.class);
public static void main(String[] args) {
logger.trace("Entering MyLogger.");
System.out.println("Hello World!");
logger.error("Test logger.error!");
logger.trace("Exiting MyLogger.");
}
}
6. src目录下新建log4j2.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<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="trace">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
7. 运行结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/b00bb9be8f63eb7b81a486b01f851289.png)
23:51:36.142 [main] TRACE MyLogger - Entering MyLogger.
Hello World!
23:51:36.143 [main] ERROR MyLogger - Test logger.error!
23:51:36.143 [main] TRACE MyLogger - Exiting MyLogger.