SpringBoot打印系统执行的sql语句及日志配置指南

 更新时间:2023年10月25日 09:02:30   作者:Congee_porridge  
这篇文章主要给大家介绍了关于SpringBoot打印系统执行的sql语句及日志配置的相关资料,在Java SpringBoot项目中如果使用了Mybatis框架,默认情况下执行的所有SQL操作都不会打印日志,需要的朋友可以参考下

直接在application.yml/properties文件中进行配置

引入依赖:

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!-- boot父依赖  可以指定版本号(指定后boot其他依赖不加版本号不报错 否则报错) -->
        <version>2.3.6.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 提供Web开发场景所需的底层所有依赖,springboot默认集成了tomcat服务器 -->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
            <!-- 点进去里面有logback、log4j和slf4j -->
            <!--  如果添加了这个依赖,SpringBoot 应用将自动使用 logback 作为应用日志框架 -->
        </dependency>
    </dependencies>

1、Mybatis内置的日志工厂

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种工具:
slf4j
Apache Commons Logging
Log4j 2
Log4j
JDK logging
具体选择哪个日志实现工具由MyBatis的内置日志工厂确定。它会使用最先找到的(按上文列举的顺序查找)。如果一个都未找到,日志功能就会被禁用。

配置log-impl:可供选择的有以下几种

在这里插入图片描述

yml中:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #这个是可以打印sql、参数、查询结果的,只会打印到控制台不会输出到日志文件中
			 #org.apache.ibatis.logging.log4j.Log4jImpl:这个不打印查询结果
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.plan.entity # 指定的包名

或properties中:

# mybatis plus
mybatis-plus.mapper-locations=classpath:mapper/*Mapper.xml
mybatis-plus.type-aliases-package=com.example.plan
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl # 重点

StdOutImpl控制台输出结果:

==>  Preparing: select id, name, sex from t_user where sex = ?
==> Parameters: 0(Integer)
<==      Total: 8

/**
 *第一行是执行的sql语句
 *第二行是传入的参数
 *第三行是返回结果的行数
 */

补充:

log-impl用于设置打印sql的日志实现,指定的值为org.apache.ibatis.logging.Log接口的其中的一个实现类

在这里以StdOutImpl为例

public class StdOutImpl implements Log {

  public StdOutImpl(String clazz) {
    // Do Nothing
  }

  @Override
  public boolean isDebugEnabled() {
    return true;
  }

  @Override
  public boolean isTraceEnabled() {
    return true;
  }

  @Override
  public void error(String s) {
    System.err.println(s);
  }

  @Override
  public void debug(String s) {
    System.out.println(s);
  }

  @Override
  public void trace(String s) {
    System.out.println(s);
  }

  @Override
  public void warn(String s) {
    System.out.println(s);
  }
}

方法里面的输出,是用的System.out/error.println方法,所以如果配置为org.apache.ibatis.logging.stdout.StdOutImpl就只会在控制台窗口打印,不会记录到日志文件。

如果需要保存打印SQL到文件就不能设置为StdOutImpl,可以设置为Slf4jImpl。部分代码如下,使用的是Log的方法,保存到文件中。

  @Override
  public void error(String s) {
    log.error(s);
  }

  @Override
  public void debug(String s) {
    log.debug(s);
  }

  @Override
  public void trace(String s) {
    log.trace(s);
  }

  @Override
  public void warn(String s) {
    log.warn(s);
  }

也可以不设置。然后对应接口所在包设置logback对应包的日志等级[debug\info\error\warn等],即下面所提到的第二种方式。
级别从高到低:OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL

2、Spring Boot集成Mybatis

logging.file.name设置日志文件:支持绝对路径、相对路径,相对路径的话是相对应用的根目录,比如logging.file.name=logs/demo.log;
默认:spring.log
logging.file.path设置日志路径:支持绝对路径、相对路径,比如 logging.file.path=logs,日志文件默认会存为 spring.log;
默认:根路径/LOG_PATH_IS_UNDEFINED/

yml中:

#spring boot集成mybatis的方式打印sql
logging:
    level:
      com.xxx.mapper: debug # 包路径为mapper文件包路径
      org.springframework: warn
      org.apache.ibatis.logging: debug
    file:
      path/name: #加不加这个配置就看你的resources目录下是否有logbackxxxx之类的xml文件,有的话会自动加载这个,识别里面的logpath。如果外部的这个日志配置和xml文件中具有相同的配置的话,哪个优先级更高一点?

此时,如果有相应的log配置文件,比如叫logback-spring.xml。

配置文件中部分内容如下:

	<!--开发环境:打印控制台-->
    <springProfile name="dev,prod,test">
        <logger name="com.example.plan" level="info"/>
    </springProfile>

    <root level="info">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="INFO_FILE"/>
        <appender-ref ref="WARNING_FILE"/>
        <appender-ref ref="ERROR_FILE"/>
    </root>
    <!-- 其中的springProfile标签指定了name,那么在application.yml文件中要启用dev,prod,test中的一个,不然输出的内容为空。logger标签中的name限定了范围。 -->

相应的yml中的logging配置:

logging:
  config: ${spring.config.location}logback-spring.xml # 不加也行,Springboot默认的日志配置文件名称为logback.xml和logback-spring.xml、logbackxxxx.xml
spring:
  profiles:
    active: dev

3、总结

sql其它日志信息简述配置
只打印到控制台不输出只打印sql到控制台仅需log-impl配置为StdOutImpl
只打印到控制台输出其它日志信息保存到文件,sql只打印到控制台,不保存到文件中log-impl配置为StdOutImpl,再加上logging的配置(logging.config指定配置文件/ resources目录下有符合spring boot自动化配置文件名的logbackxxx.xml/ yml中logging.level/file配置完整一些)
打印到控制台且输出到日志文件中输出sql和其它日志信息保存到文件中,sql也打印到控制台log-impl为Slf4jImpl/或者不设置,总之不能设置为StdOutImpl,再加上logging的配置即可

配置为logback-test.xml后,控制台的输出:

15:50:13,315 |-INFO in ch.qos.logback.classic.LoggerContext[logback] - Found resource [logback-test.xml] at [file:/Users/congee/Desktop/code/GService/service/target/classes/logback-test.xml]
15:50:13,342 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
15:50:13,345 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Will scan for changes in [file:/Users/congee/Desktop/code/GService/service/target/classes/logback-test.xml]
15:50:13,345 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - Setting ReconfigureOnChangeTask scanning period to 10 seconds
15:50:13,357 |-INFO in ch.qos.logback.classic.joran.action.ContextNameAction - Setting logger context name as [logback]
15:50:13,357 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
15:50:13,358 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [CONSOLE]
15:50:13,362 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
15:50:13,381 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
15:50:13,382 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [INFO_FILE]
15:50:13,382 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
15:50:13,386 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@1858609436 - No compression will be used
15:50:13,387 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@1858609436 - Will use the pattern /Users/congee/log/monitor//log-info-%d{yyyy-MM-dd}.%i.log for the active file
15:50:13,388 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7276c8cd - The date pattern is ‘yyyy-MM-dd’ from file name pattern ‘/Users/congee/log/monitor//log-info-%d{yyyy-MM-dd}.%i.log’.
15:50:13,388 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7276c8cd - Roll-over at midnight.
15:50:13,389 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7276c8cd - Setting initial period to Thu Apr 13 15:50:13 CST 2023
15:50:13,389 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7276c8cd - SizeAndTimeBasedFNATP is deprecated. Use SizeAndTimeBasedRollingPolicy instead
15:50:13,389 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@7276c8cd - For more information see http://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy
15:50:13,392 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[INFO_FILE] - Active log file name: /Users/congee/log/monitor//log-info-2023-04-13.0.log
15:50:13,392 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[INFO_FILE] - File property is set to [null]
15:50:13,392 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
15:50:13,392 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [WARNING_FILE]
15:50:13,392 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
15:50:13,393 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@1414147750 - No compression will be used
15:50:13,393 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@1414147750 - Will use the pattern /Users/congee/log/monitor//log-warning-%d{yyyy-MM-dd}.%i.log for the active file
15:50:13,393 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2e3fc542 - The date pattern is ‘yyyy-MM-dd’ from file name pattern ‘/Users/congee/log/monitor//log-warning-%d{yyyy-MM-dd}.%i.log’.
15:50:13,393 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2e3fc542 - Roll-over at midnight.
15:50:13,393 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2e3fc542 - Setting initial period to Thu Apr 13 15:50:13 CST 2023
15:50:13,394 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2e3fc542 - SizeAndTimeBasedFNATP is deprecated. Use SizeAndTimeBasedRollingPolicy instead
15:50:13,394 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@2e3fc542 - For more information see http://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy
15:50:13,394 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[WARNING_FILE] - Active log file name: /Users/congee/log/monitor//log-warning-2023-04-13.0.log
15:50:13,394 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[WARNING_FILE] - File property is set to [null]
15:50:13,394 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender]
15:50:13,394 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [ERROR_FILE]
15:50:13,394 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
15:50:13,395 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@22069592 - No compression will be used
15:50:13,395 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy@22069592 - Will use the pattern /Users/congee/log/monitor//log-error-%d{yyyy-MM-dd}.%i.log for the active file
15:50:13,395 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4524411f - The date pattern is ‘yyyy-MM-dd’ from file name pattern ‘/Users/congee/log/monitor//log-error-%d{yyyy-MM-dd}.%i.log’.
15:50:13,395 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4524411f - Roll-over at midnight.
15:50:13,395 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4524411f - Setting initial period to Thu Apr 13 15:50:13 CST 2023
15:50:13,395 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4524411f - SizeAndTimeBasedFNATP is deprecated. Use SizeAndTimeBasedRollingPolicy instead
15:50:13,395 |-WARN in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@4524411f - For more information see http://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy
15:50:13,395 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[ERROR_FILE] - Active log file name: /Users/congee/log/monitor//log-error-2023-04-13.0.log
15:50:13,395 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[ERROR_FILE] - File property is set to [null]
15:50:13,396 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@91:31 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]]
15:50:13,396 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@92:54 - no applicable action for [logger], current ElementPath is [[configuration][springProfile][logger]]
15:50:13,396 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO
15:50:13,396 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [CONSOLE] to Logger[ROOT]
15:50:13,396 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [INFO_FILE] to Logger[ROOT]
15:50:13,396 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [WARNING_FILE] to Logger[ROOT]
15:50:13,396 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [ERROR_FILE] to Logger[ROOT]
15:50:13,396 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
15:50:13,396 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@401e7803 - Registering current configuration as safe fallback point

配置完号后的紧接着的日志输出:

2023-04-13 15:50:18.450 [background-preinit] INFO org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 6.1.6.Final
2023-04-13 15:50:18.689 [main] INFO c.u.j.c.EnableEncryptablePropertiesBeanFactoryPostProcessor - Post-processing PropertySource instances
2023-04-13 15:50:18.715 [main] INFO c.u.j.EncryptablePropertySourceConverter - Converting PropertySource configurationProperties [org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource] to AOP Proxy

可以直观的感受到前面日志的时间格式的变化。

到此这篇关于SpringBoot打印系统执行的sql语句及日志配置指南的文章就介绍到这了,更多相关SpringBoot打印系统执行sql语句内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 创建Java线程安全类的七种方法

    创建Java线程安全类的七种方法

    线程安全是指某个方法或某段代码,在多线程中能够正确的执行,不会出现数据不一致或数据污染的情况,我们把这样的程序称之为线程安全的,反之则为非线程安全的,下面这篇文章主要给大家介绍了关于创建Java线程安全类的七种方法,需要的朋友可以参考下
    2022-06-06
  • java数据结构图论霍夫曼树及其编码示例详解

    java数据结构图论霍夫曼树及其编码示例详解

    这篇文章主要为大家介绍了java数据结构图论霍夫曼树及其编码示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2021-11-11
  • Java中使用DOM4J生成xml文件并解析xml文件的操作

    Java中使用DOM4J生成xml文件并解析xml文件的操作

    这篇文章主要介绍了Java中使用DOM4J来生成xml文件和解析xml文件的操作,今天通过代码给大家展示了解析xml文件和生成xml文件的方法,需要的朋友可以参考下
    2021-09-09
  • MyBatis-Plus实现公共字段自动填充功能详解

    MyBatis-Plus实现公共字段自动填充功能详解

    在开发中经常遇到多个实体类有共同的属性字段,这些字段属于公共字段,也就是很多表中都有这些字段,能不能对于这些公共字段在某个地方统一处理,来简化开发呢?MyBatis-Plus就提供了这一功能,本文就来为大家详细讲讲
    2022-08-08
  • MyBatis使用注解开发实现步骤解析

    MyBatis使用注解开发实现步骤解析

    这篇文章主要介绍了MyBatis使用注解开发实现步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • 关于String.format()格式化输出方式

    关于String.format()格式化输出方式

    String.format()是Java的格式化输出方法,支持多种数据类型和格式化选项,它在格式化和拼接字符串时具有较高的灵活性,但效率相对较低,特别是在处理大量数据时,在实际编程中,应根据具体需求选择合适的字符串拼接方式
    2024-12-12
  • java中的反射应用实现

    java中的反射应用实现

    这篇文章主要介绍了java中的反射应用实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • SpringCloud Gateway的路由,过滤器和限流解读

    SpringCloud Gateway的路由,过滤器和限流解读

    这篇文章主要介绍了SpringCloud Gateway的路由,过滤器和限流解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • 将SpringBoot属性配置类@ConfigurationProperties注册为Bean的操作方法

    将SpringBoot属性配置类@ConfigurationProperties注册为Bean的操作方法

    在现代 Spring Boot 应用开发中,外部化配置(Externalized Configuration)是实现应用灵活性和可维护性的核心机制之一,然而,许多开发者在使用的时候经常会遇到如何确保该配置类被正确注册为 Spring 容器中的 Bean,下面小编为大家详细说说
    2025-12-12
  • Spring Boot 快速入门指南

    Spring Boot 快速入门指南

    Spring 框架是非常著名的 Java 开源框架,历经十多年的发展,整个生态系统已经非常完善甚至是繁杂,Spring Boot 正是为了解决这个问题而开发的,为 Spring 平台和第三方库提供了开箱即用的设置,只需要很少的配置就可以开始一个 Spring 项目
    2017-03-03

最新评论