日志的好处

如果一个数据库操作出现异常,查看日志进行排错是最佳方式

MyBatis日志设置

image.png
image.png

  1. //实体类
  2. public class User {
  3. int id;
  4. String name;
  5. String pwd;
  6. public User() {}
  7. public User(int id, String name, String pwd) {
  8. this.id = id;
  9. this.name = name;
  10. this.pwd = pwd;
  11. }
  12. public int getId() {
  13. return id;
  14. }
  15. public void setId(int id) {
  16. this.id = id;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public String getPwd() {
  25. return pwd;
  26. }
  27. public void setPwd(String pwd) {
  28. this.pwd = pwd;
  29. }
  30. @Override
  31. public String toString() {
  32. return "User{" +
  33. "id=" + id +
  34. ", name='" + name + '\'' +
  35. ", pwd='" + pwd + '\'' +
  36. '}';
  37. }
  38. }

STDOUT_LOGGING

//UserMapper接口
public interface UserMapper {
    //测试 STDOUT_LOGGING 日志实现
    List<User> getListOfUser();
}
<?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>
    <settings>
        <!-- 测试 STDOUT_LOGGING 日志实现 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;characterSetResults=utf-8&amp;useSSL=false&amp;verifyServerCertificate=false&amp;autoReconnect=true&amp;autoReconnectForPools=true&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="txq199807031578"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 每一个mapper.xml都需要在MyBatis核心配置文件中注册 -->
    <mappers>
        <mapper resource="com/comprehensive/dao/UserMapper.xml"/>
    </mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=绑定一个对应的Dao/Mapper接口 -->
<!-- 等同于JDBC中的UserDaoImpl(接口实现类),转变为Mapper配置文件 -->
<mapper namespace="com.comprehensive.dao.UserMapper">
    <!-- 测试 STDOUT_LOGGING 日志实现 -->
    <select id="getListOfUser" resultType="com.comprehensive.pojo.User">
        select * from mybatis.user
    </select>
</mapper>
//测试类
public class UserMapper_Test {
    @Test
    //测试 STDOUT_LOGGING 日志实现
    public void test() {
        SqlSession sqlSession = MyBatis_Util.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(mapper.getListOfUser());
        sqlSession.close();
    }
}

image.png

LOG4J

Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

  • 首先我们需要导入LOG4J依赖包,导入配置如下

    <!-- 导入log4j依赖包 -->
    <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    </dependencies>
    
  • 在resources目录下创建log4j.properties文件 ```markdown

    将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码

    log4j.rootLogger=DEBUG,console,file

控制台输出的相关设置

log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

文件输出的相关设置

log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/comprehensive.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

日志输出级别

log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG


- 开始配置环境
```java
public interface UserMapper {
    //测试 LOG4J 日志实现
    User getUserById(int id);
}
<?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>
    <settings>
        <!-- 测试 LOG4J 日志实现 -->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;characterSetResults=utf-8&amp;useSSL=false&amp;verifyServerCertificate=false&amp;autoReconnect=true&amp;autoReconnectForPools=true&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="txq199807031578"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 每一个mapper.xml都需要在MyBatis核心配置文件中注册 -->
    <mappers>
        <mapper resource="com/comprehensive/dao/UserMapper.xml"/>
    </mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace=绑定一个对应的Dao/Mapper接口 -->
<!-- 等同于JDBC中的UserDaoImpl(接口实现类),转变为Mapper配置文件 -->
<mapper namespace="com.comprehensive.dao.UserMapper">
    <!-- 测试 LOG4J 日志实现 -->
    <select id="getUserById" parameterType="int" resultType="com.comprehensive.pojo.User">
        select * from mybatis.user where id=#{id}
    </select>
</mapper>
//测试类
public class UserMapper_Test {
    @Test
    // 测试 LOG4J 日志实现
    public void test2() {
        SqlSession sqlSession = MyBatis_Util.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(mapper.getUserById(1));
        sqlSession.close();
    }
}

image.png