方法如下
1、去掉所有log4j的相关依赖,主要有:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
以及
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
2、SpringBoot项目中依赖包spring-boot-starter中已经包含spring-boot-starter-logging,该依赖包就是默认的logback日志框架,则不需额外引入。但是要看项目中有没有排除掉,如下,有的话删除掉或者注释掉就OK了
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
以下是非springboot项目则需要添加以下依赖
<!-- logback日志配置开始 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</dependency>
<!-- logback日志配置结束 -->
3、删除项目下/src/main/resources目录下的log4j.properties,并在该目录添加logback.xml文件,logback.xml文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="30 seconds">
<property name="logBase" value="./logs"/>
<property name="log.archive.max.file.size" value="60MB"/>
<property name="log.archive.max.history" value="15"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
<!-- %highlight(%-5level)日志级别高亮显示 -->
%date [%thread] %highlight(%-5level) %logger{10} [%file:%line] %msg%n
</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 服务日志 -->
<appender name="GW_ROOT_LOG"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logBase}/${serviceName}_ROOT.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${logBase}/${serviceName}_ROOT-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxHistory>${log.archive.max.history}</maxHistory>
<maxFileSize>${log.archive.max.file.size}</maxFileSize>
</rollingPolicy>
<encoder>
<pattern>%date [%thread] [%X{requestId}] %highlight(%-5level) %logger{10} [%file:%line] %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
4、最后在application.yml中替换logging的指向地址
logging:
config: classpath:logback.xml