一、背景
在 debug 程序过程中,将框架中原有的日志打印到控制台中也很有利于 debug 的进行。这里对 spring framework 的日志进行配置并且激活。
二、步骤
(一)添加依赖
dependencies {
// Logback 实现
implementation 'ch.qos.logback:logback-classic:1.2.13'
// SLF4J API
implementation 'org.slf4j:slf4j-api:1.7.36'
// 桥接 Commons Logging (JCL)
implementation 'org.slf4j:jcl-over-slf4j:1.7.36'
// 桥接 Java Util Logging (JUL)
implementation 'org.slf4j:jul-to-slf4j:1.7.36'
// 排除其他日志框架(同上)
configurations.all {
// 排除所有 Log4j2 相关依赖
exclude group: 'org.apache.logging.log4j', module: 'log4j-core'
exclude group: 'org.apache.logging.log4j', module: 'log4j-api'
exclude group: 'org.apache.logging.log4j', module: 'log4j-slf4j-impl'
exclude group: 'org.apache.logging.log4j', module: 'log4j-slf4j2-impl'
exclude group: 'org.apache.logging.log4j', module: 'log4j-jcl'
exclude group: 'org.apache.logging.log4j', module: 'log4j-jul'
// 确保没有其他 SLF4J 实现
exclude group: 'org.slf4j', module: 'slf4j-simple'
exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}
}
(二)添加配置文件
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 控制台输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- 设置 Spring 日志级别 -->
<logger name="org.springframework" level="DEBUG" />
<logger name="org.springframework.beans" level="TRACE" />
<logger name="org.springframework.context" level="DEBUG" />
<logger name="org.springframework.web" level="DEBUG" />
<logger name="org.springframework.transaction" level="TRACE" />
<!-- 根日志级别 -->
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
三、测试是否正常
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 激活 spring framework 日志模块。
* 测试框架日志打印是否正常。
*/
public class LogTest {
private static final Logger logger = LoggerFactory.getLogger(LogTest.class);
public static void main(String[] args) {
logger.info("Logback 成功运行在 Java {}", System.getProperty("java.version"));
}
}
效果