背景:
我们日常操作数据库的过程一般都是使用mybatis中执行sql操作,有时候为了确认mybatis拼接的sql是否正确,就需要在日志中打印出具体的sql语句,对应的入参以及数据库的返回值
打印mybatis的sql日志:
一.sql日志输出到控制台,修改mybatis-config文件,指定如下配置:
setting name="logImpl" value="STDOUT_LOGGING"/>
二.sql日志输出到文件,修改mybatis-config文件,指定如下配置
2.1
setting name="logPrefix" value="sqlLogFileName."/>
setting name="logImpl" value="SLF4J"/>
2.2 logback或者log4j增加配置:
appender("ROLLING", RollingFileAppender) {
encoder(PatternLayoutEncoder) {
Pattern = "[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] [%thread] [%logger{50}] >>> %msg%n"
}
rollingPolicy(SizeAndTimeBasedRollingPolicy) {
fileNamePattern = "log-%d{yyyy-MM-dd}-%i.log"
maxFileSize = "2GB"
}
}
appender("ROLLING-ASYNC", AsyncAppender) {
queueSize = 40960
neverBlock = true
appenderRef("ROLLING")
}
//最关键的一句
logger("sqlLogFileName", DEBUG, ["ROLLING-ASYNC"], false)
关键是日志级别要修改成DEBUG级别
日志效果:
[2023-07-07 17:39:49.533] [DEBUG] [**-thread-2] [org.mybatis.spring.SqlSessionUtils] >>> Creating a new SqlSession
[2023-07-07 17:39:49.647] [DEBUG] [**-thread-2] [dao.***Mapper.selectByStatus] >>> ==> Preparing: select user_id, status, is_deleted, create_time, update_time from user where status = ?
[2023-07-07 17:39:49.650] [DEBUG] [**-thread-2] [dao.***Mapper.selectByStatus] >>> ==> Parameters: 0(Byte)
[2023-07-07 17:39:51.620] [DEBUG] [**-thread-2] [dao.***Mapper.selectByStatus] >>> = Total: 805
[2023-07-07 17:39:51.622] [DEBUG] [**-thread-2] [org.mybatis.spring.SqlSessionUtils] >>> Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7b989b3b]
主要信息包括执行的sql语句,sql的入参,sql的返回值(对update或者insert语句很有用).
参考资料:
http://www.tianshouzhi.com/api/tutorials/mybatis/375
https://www.cnblogs.com/phpdragon/p/12107146.html