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進行日志記錄,實現了兩者的集成。