1. pom.xml引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 这里需要排除spring自带的日志,否则会有冲突 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.0</version>
</dependency>
<!-- 这里引入了slf4j的实现,否则会提示SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.13.0</version>
</dependency>
</dependencies>
2. java程序调用
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class HelloWorld {
//官方建议使用静态成员变量来获取logger实例
private static final Logger logger = LogManager.getLogger("HelloWorld");
public static void main(String[] args) {
logger.info("Hello, World!");
}
}
3. 配置文件log4j2.xml
如果不提供配置文件,spring boot会使用内置的配置文件
3.1 配置spring boot的log配置路径
src/main/resources/application.yml
logging:
config: classpath:log4j2.xml //表示读取放在resources根目录的名称log4j2.xml的文件
3.2 配置log4j2.xml文件
src/main/resources/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>
<!-- 定义日志文件格式和储存位置 -->
<RollingFile name="FileLogger"
fileName="logs/app.log"
filePattern="logs/app-%d{yyyy-MM-dd}.log"
append="true">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<!-- 可以设置文件分片策略(时间,大小) -->
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100MB"/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<!-- 设置日志启动的等级,并绑定对应的日志配置 -->
<Root level="ERROR">
<AppenderRef ref="Console"/>
<AppenderRef ref="FileLogger"/>
</Root>
</Loggers>
</Configuration>
网友评论