首先排除自带的log依赖,然后导入log4j2依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<!-- 排除自带的日志工具依赖,为了项目使用Log4j2日志打印工具 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 导入log4j2依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
在resources下创建log4j2-spring.xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<properties>
<!-- 文件输出格式 -->
<property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
</properties>
<appenders>
<Console name="CONSOLE" target="system_out">
<PatternLayout pattern="${PATTERN}"/>
</Console>
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
<!--当app.log达到5MB时,就会自动生成gz压缩文件到/logs下,并清空app.log,继续输出到app.log,以此循环。-->
<SizeBasedTriggeringPolicy size="5 MB"/>
</RollingFile>
</appenders>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<loggers>
<!--包名-->
<logger name="com.xxx.xxx" level="debug"/>
<root level="info">
<appenderref ref="CONSOLE"/>
<appender-ref ref="RollingFile"/>
</root>
</loggers>
</configuration>
测试类
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogTest {
@Test
public void test() {
Logger log = LoggerFactory.getLogger(LogTest.class);
log.warn("this is message {}", 1);
Exception ex = new Exception("this is a message.");
log.error("a new exeception", ex);
log.trace("trace message.");
log.info("info message.");
for (int i = 0; i < 120000; i++)
log.debug("debug message:{}={}", "line", i);
}
}
参考:
https://www.cnblogs.com/keeya/p/10101547.html
https://www.cnblogs.com/songxingzhu/p/8867817.html
网友评论