Mybatis入门-03-日志工厂

一、 前言

一切当以官方文档为基准。

参考网站:

参考视频:

本文之前的操作步骤:

  1. Mybatis入门-第一个程序
  2. Mybatis入门-02-增删改查及配置(属性、别名、映射器)

前置内容:

  • Java
  • maven
  • MySQL
  • JDBC
  • JavaWeb中持久化层的一些知识,如POJO

环境:

  • Java11
  • IDEA 2019.3.3
  • MySQL8
  • mybatis3

路径:

image-20200911151112604

目的:使用日志,更好地排错。

二、设置

查看Mybatis官方中文文档-xml配置-settingslogImpl项:

设置名 描述 有效值 默认值
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING 未设置

1.STDOUT_LOGGING

按照文档,将mybatis-config.xml设置为:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties resource="db.properties"></properties>
    
<!--====================add=====================-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<!--============================================-->
    
    <typeAliases>
        <package name="com.duzhuan.pojo"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper class="com.duzhuan.dao.UserMapper"></mapper>
    </mappers>
</configuration>

注意顺序,若不知道顺序,可以先随便放置,IDEA会报错:

image-20200911153927061

使用测试样例getUerListById进行测试:

没有启用日志前:

image-20200911154308735

启用日志后:

image-20200911154428477

可以看到返回了许多关键的信息,圈起来的是SQL语句。

2.SLF4J+Log4j2

目前最流行的日志门面是SLF4J,虽然Log4J也是日志门面,但是因为功能强大,性能优越,一般还是将其看作是日志实现。

依赖:

        <!--使用slf4j 作为日志门面-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!--使用 log4j2 的适配器进行绑定-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.12.1</version>
            <scope>test</scope>
        </dependency>


        <!--log4j2 日志门面-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.12.1</version>
        </dependency>
        <!--log4j2 日志实现-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.12.1</version>
        </dependency>

这里参考bdqfork创作-SLF4J日志级别以及使用场景,SFL4J+Log4J2的日志级别:

  • trace(最低)
  • debug
  • info
  • warn
  • error(最高)

柠檬五个半-log4j使用教程里获取配置,部分备注参考黑马程序员-2020年Java进阶教程,全面学习多种java日志框架-P33 log4j2 配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!--
    status="debug" 日志框架本身的级别
    configuration还有个属性是 monitorInterval = 5,自动加载配置文件的最小间隔时间,单位是秒
-->
<configuration status="debug">

    <!--
        集中配置属性进行管理,使用时通过:${}
    -->
    <properties>
        <property name="LOG_HOME">./logs</property>
    </properties>

    <!--日志处理器-->
    <!--先定义所有的appender -->
    <appenders>
        <!--这个输出控制台的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!--             控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
            <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
            <!--             这个都知道是输出日志的格式 -->
            <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} [%-5level] %class{36} %L %M - %msg%xEx%n"/>
        </Console>

        <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
        <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
        <File name="log" fileName="${LOG_HOME}/mybatis-log.log" append="false">
            <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} [%-5level] %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <!--
            添加过滤器ThresholdFilter,可以有选择的输出某个级别以上的类别
            onMatch="ACCEPT" onMismatch="DENY"意思是匹配就接受,否则直接拒绝
        -->
        <File name="ERROR" fileName="${LOG_HOME}/mybatis-error.log">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} [%-5level] %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <!--
            使用随机读写流的日志文件输出appender,性能提高
        -->
        <RandomAccessFile name="accessFile" fileName="${LOG_HOME}/mybatis-access.log">
            <PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} [%-5level] %class{36} %L %M - %msg%xEx%n"/>
        </RandomAccessFile>

        <!--
            这个会打印出所有的信息,每次大小超过size,
            则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,
            作为存档
         -->
        <RollingFile name="RollingFile" fileName="${LOG_HOME}/mybatis-web.log"
                     filePattern="logs/$${date:yyyy-MM}/web-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} [%-5level] %class{36} %L %M - %msg%xEx%n"/>
            <SizeBasedTriggeringPolicy size="2MB"/>
        </RollingFile>
    </appenders>


    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    <loggers>
        <!--使用rootLogger配置   日志级别level="trace" -->
        <root level="trace">
            <!--制定日志使用的处理器-->
            <appender-ref ref="log"/>
            <appender-ref ref="ERROR" />
            <appender-ref ref="Console"/>
            <appender-ref ref="accessFile"/>
            <appender-ref ref="RollingFile"/>
        </root>
    </loggers>
</configuration>

将mybatis-config.xml中name="logImpl"setting标签的value的值设为SLF4J

    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>

运行UserMapperTest中的测试样例,这里运行getUserByIdTest:

    @Test
    public void getUserByIdTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();
    }

第一次使用时,还会在设置好的目录里创建日志文件:

image-20200911223540185

根据上面的注释,可以知道这里记录最完整的是mybatis-access.logmybatis-web.log,用记事本打开可以看到:

2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.logging.LogFactory 105 setImplementation - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.logging.LogFactory 105 setImplementation - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.VFS 116 getClass - Class not found: org.jboss.vfs.VFS
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.JBoss6VFS 149 setInvalid - JBoss 6 VFS API is not available in this environment.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.VFS 116 getClass - Class not found: org.jboss.vfs.VirtualFile
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.VFS$VFSHolder 64 createVFS - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.VFS$VFSHolder 74 createVFS - Using VFS adapter org.apache.ibatis.io.DefaultVFS
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 220 findJarForResource - Find JAR URL: file:/D:/IdeaProject/MyBaitsLearn/mybatis-01/target/classes/com/duzhuan/pojo
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 247 findJarForResource - Not a JAR: file:/D:/IdeaProject/MyBaitsLearn/mybatis-01/target/classes/com/duzhuan/pojo
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 100 list - Reader entry: User.class
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 111 list - Listing file:/D:/IdeaProject/MyBaitsLearn/mybatis-01/target/classes/com/duzhuan/pojo
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 220 findJarForResource - Find JAR URL: file:/D:/IdeaProject/MyBaitsLearn/mybatis-01/target/classes/com/duzhuan/pojo/User.class
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 247 findJarForResource - Not a JAR: file:/D:/IdeaProject/MyBaitsLearn/mybatis-01/target/classes/com/duzhuan/pojo/User.class
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.DefaultVFS 100 list - Reader entry: ����   7 :
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.io.ResolverUtil 288 addIfMatching - Checking to see if class com.duzhuan.pojo.User matches criteria [is assignable to Object]
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource 363 forceCloseAll - PooledDataSource forcefully closed/removed all connections.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource 363 forceCloseAll - PooledDataSource forcefully closed/removed all connections.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource 363 forceCloseAll - PooledDataSource forcefully closed/removed all connections.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource 363 forceCloseAll - PooledDataSource forcefully closed/removed all connections.
2020-09-11 at 22:41:49 CST [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction 137 openConnection - Opening JDBC Connection
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource 434 popConnection - Created connection 1727420902.
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction 101 setDesiredAutoCommit - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@66f659e6]
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 debug - ==>  Preparing: select * from mybatis.user where name like concat('%',?,'%')
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 debug - ==> Parameters: a(String)
2020-09-11 at 22:41:50 CST [TRACE] org.apache.ibatis.logging.jdbc.BaseJdbcLogger 143 trace - <==    Columns: id, name, pwd
2020-09-11 at 22:41:50 CST [TRACE] org.apache.ibatis.logging.jdbc.BaseJdbcLogger 143 trace - <==        Row: 1, admin, 123456
2020-09-11 at 22:41:50 CST [TRACE] org.apache.ibatis.logging.jdbc.BaseJdbcLogger 143 trace - <==        Row: 2, Jax, 123456
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 debug - <==      Total: 2
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction 123 resetAutoCommit - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@66f659e6]
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.transaction.jdbc.JdbcTransaction 91 close - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@66f659e6]
2020-09-11 at 22:41:50 CST [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource 391 pushConnection - Returned connection 1727420902 to pool.

格式设置得好找一点的话在控制台也可以比较轻松找到:

image-20200911224305963

posted @ 2020-09-11 22:49  杜撰丶  阅读(291)  评论(0编辑  收藏  举报