项目依赖的版本号如下:
<properties> <lombok.version>1.18.2</lombok.version> <slf4j.version>1.7.36</slf4j.version> <log4j.version>2.17.2</log4j.version> </properties>
项目的依赖包如下:
<dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j.version}</version> </dependency> </dependencies>
参考文档
Log4j Runtime Dependencies
下图是 log4j-slf4j-impl 的依赖树:
虽然依赖树中已经包含了 log4j-api 的依赖,但是在尝试不指明版本的情况下,引用了 2.13.x 版本而非 2.17.2 版本,还因此报出 NoSuchMethodError;
但是 log4j-core 依赖的 scope 是 runtime,所以我们在项目中引用它。
创建文件 src/main/resources/log4j2.xml
,内容如下:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="INFO"> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%m%n"/> </Console> <File name="FILE_APPENDER" fileName="logs/app.log"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> </File> <Async name="ASYNC_FILE_APPENDER"> <AppenderRef ref="FILE_APPENDER"/> </Async> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="STDOUT" /> <AppenderRef ref="ASYNC_FILE_APPENDER"/> </Root> </Loggers> </Configuration>
参考更多 Log4j 2.x Appenders