Maven添加依赖:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.14.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
Gradle添加依赖:
implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.14.1'
implementation 'org.slf4j:slf4j-api:1.7.32'
在log4j2.xml文件中添加如下配置:
<Configuration status="INFO">
<Appenders>
...
</Appenders>
<Loggers>
...
</Loggers>
<Properties>
<Property name="log4jContextSelector" value="org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"/>
</Properties>
</Configuration>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClass {
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
public void doSomething() {
logger.debug("Debug message");
logger.info("Info message");
logger.warn("Warn message");
logger.error("Error message");
}
}
通过以上步骤,你就可以在项目中使用log4j2作为日志实现工具,同时使用SLF4J进行日志记录,实现了两者的集成。