SpringBoot项目中打印SQL日志及结果(Logback版)📝
在SpringBoot开发中,调试SQL语句是常见需求,今天我们就来聊聊如何通过Logback配置优雅地打印SQL日志和结果!🚀
1.基础配置🔧
首先在`application.yml`中开启Hibernate的SQL日志显示:
```yaml
spring:
jpa:
show-sql:true
properties:
hibernate:
format_sql:true
```
但这只能显示基本SQL,无法显示参数和结果。我们需要更强大的Logback配置!💪
2.Logback高级配置📜
在`logback-spring.xml`中添加以下配置:
```xml
%d{HH:mm:ss.SSS}[%thread]%-5level%logger{36}-%msg%n
```
3.效果展示✨
配置完成后,控制台会显示完整的SQL执行过程:
```
14:25:36.123[http-nio-8080-exec-1]DEBUGorg.hibernate.SQL-
select
user0_.idasid1_0_,
user0_.nameasname2_0_
from
usersuser0_
where
user0_.name=?
14:25:36.124[http-nio-8080-exec-1]TRACEorg.hibernate.type.descriptor.sql.BasicBinder-bindingparameter[1]as[VARCHAR]-[John]
14:25:36.125[http-nio-8080-exec-1]DEBUGorg.hibernate.loader.Loader-Resultsetrow:0
14:25:36.126[http-nio-8080-exec-1]DEBUGorg.hibernate.loader.Loader-Resultrow:EntityKey[com.example.User1]
```
4.进阶技巧🎯
如果想更简洁地格式化SQL日志,可以使用`p6spy`等第三方工具:
```xml
com.github.gavlyukovskiy
p6spy-spring-boot-starter
1.8.1
```
然后在`spy.properties`中配置:
```properties
appender=com.p6spy.engine.spy.appender.Slf4JLogger
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=%(executionTime)ms|%(category)|connection%(connectionId)|%(sqlSingleLine)
```
这样就能获得更友好的SQL日志格式啦!🌈
希望这篇小文能帮你更好地调试SpringBoot中的SQL查询!Happycoding!💻😊
在SpringBoot开发中,调试SQL语句是常见需求,今天我们就来聊聊如何通过Logback配置优雅地打印SQL日志和结果!🚀
1.基础配置🔧
首先在`application.yml`中开启Hibernate的SQL日志显示:
```yaml
spring:
jpa:
show-sql:true
properties:
hibernate:
format_sql:true
```
但这只能显示基本SQL,无法显示参数和结果。我们需要更强大的Logback配置!💪
2.Logback高级配置📜
在`logback-spring.xml`中添加以下配置:
```xml
```
3.效果展示✨
配置完成后,控制台会显示完整的SQL执行过程:
```
14:25:36.123[http-nio-8080-exec-1]DEBUGorg.hibernate.SQL-
select
user0_.idasid1_0_,
user0_.nameasname2_0_
from
usersuser0_
where
user0_.name=?
14:25:36.124[http-nio-8080-exec-1]TRACEorg.hibernate.type.descriptor.sql.BasicBinder-bindingparameter[1]as[VARCHAR]-[John]
14:25:36.125[http-nio-8080-exec-1]DEBUGorg.hibernate.loader.Loader-Resultsetrow:0
14:25:36.126[http-nio-8080-exec-1]DEBUGorg.hibernate.loader.Loader-Resultrow:EntityKey[com.example.User1]
```
4.进阶技巧🎯
如果想更简洁地格式化SQL日志,可以使用`p6spy`等第三方工具:
```xml
com.github.gavlyukovskiy
p6spy-spring-boot-starter
1.8.1
```
然后在`spy.properties`中配置:
```properties
appender=com.p6spy.engine.spy.appender.Slf4JLogger
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=%(executionTime)ms|%(category)|connection%(connectionId)|%(sqlSingleLine)
```
这样就能获得更友好的SQL日志格式啦!🌈
希望这篇小文能帮你更好地调试SpringBoot中的SQL查询!Happycoding!💻😊
6107

被折叠的 条评论
为什么被折叠?



