添加pom依赖:
<!-- log start -->
<dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency> <!-- 后向兼容:使用Log4j2实现log2j1.x的接口 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency> <!-- 桥接:告诉Slf4j使用Log4j2 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.2</version>
</dependency>
<dependency> <!-- 桥接:告诉commons logging使用Log4j2 -->
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
<!-- log end -->
根目录下创建log4j2.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<!-- Log4j 2.x 配置文件。每30秒自动检查和应用配置文件的更新; -->
<Configuration status="warn" monitorInterval="30" strict="true" schema="Log4J-V2.2.xsd">
<Appenders>
<!-- 输出到控制台 -->
<Console name="Console" target="SYSTEM_OUT">
<!-- 需要记录的级别 -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" />
</Console>
<!-- 输出到文件,按天或者超过80MB分割 -->
<RollingFile name="RollingFile" fileName="logs/trace.log" append="true"
filePattern="logs/$${date:yyyy-MM}/trace-%d{yyyy-MM-dd}-%i.log.gz">
<!-- 需要记录的级别 -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" />
<Policies>
<!-- <OnStartupTriggeringPolicy /> -->
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="80 MB" />
</Policies>
</RollingFile>
<!-- 输出告警和错误到文件,按天或者超过80MB分割 -->
<RollingFile name="RollingErrorFile" fileName="logs/error.log" append="true"
filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
<!-- 需要记录的级别 -->
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" />
<Policies>
<!-- <OnStartupTriggeringPolicy /> -->
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="80 MB" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="info"> <!-- 全局配置 -->
<AppenderRef ref="Console" />
<AppenderRef ref="RollingFile"/>
<AppenderRef ref="RollingErrorFile"/>
</Root>
<!-- 为sql语句配置特殊的Log级别,方便调试 -->
<!-- <Logger name="com.xjj.dao" level="${log.sql.level}" additivity="false">
<AppenderRef ref="Console" />
</Logger> -->
</Loggers>
</Configuration>