Mybatis-第N篇配置log4j1、log4j2打印执行的sql语句

1、log4j1配置

   目录结构:

  Mybatis-第N篇配置log4j1、log4j2打印执行的sql语句

   conf.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>

    <settings>
       <!-- 配置用于控制台输出sql日志。低版本的mybatis不支持logImpl -->
       <setting name="logImpl" value="LOG4J"/>
    </settings>
    
    <environments default="oracle">
        <environment id="oracle">
            <!-- 指定事务管理类型,type="JDBC"指直接使用JDBC的提交与回滚   -->
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
                <property name="username" value="scott" />
                <property name="password" value="12345" />
            </dataSource>
        </environment>
        <environment id="mysql">
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/world" />
                <property name="username" value="root" />
                <property name="password" value="12345" />
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <!-- 注册empMapper.xml文件-->
        <mapper resource="com/lfy/mapping/empMapper.xml"/>
    </mappers>
    
</configuration>

  log4j.properties

#log4j-1
#全局日志配置
log4j.rootLogger=ERROR,stdout
#MyBatis日志配置
log4j.logger.com.lfy.mapping.empMapper=DEBUG
#控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p[%c] - %m%n

   empMapper.xml

<?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">
<!-- 为这个mapper指定一个唯一的namespace-->
<mapper namespace="com.lfy.mapping.empMapper">
    <select id="getEmp" parameterType="int" resultType="com.lfy.bean.Emp">
        select * from emp where empno=#{empno}
    </select>
</mapper>

   Emp.java

package com.lfy.bean;

import java.util.Date;

public class Emp {

    private Integer empno;
    private String ename;
    private String job;
    private Integer mgr;
    private Date hireDate;
    private Integer sal;
    private Integer comm;
    private Integer deptno;
    
    public Integer getEmpno() {
        return empno;
    }
    public void setEmpno(Integer empno) {
        this.empno = empno;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public Integer getMgr() {
        return mgr;
    }
    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }
    public Date getHiredate() {
        return hireDate;
    }
    public void setHiredate(Date hiredate) {
        hireDate = hiredate;
    }
    public Integer getSal() {
        return sal;
    }
    public void setSal(Integer sal) {
        this.sal = sal;
    }
    public Integer getComm() {
        return comm;
    }
    public void setComm(Integer comm) {
        this.comm = comm;
    }
    public Integer getDeptno() {
        return deptno;
    }
    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }
    
    @Override
    public String toString() {
        
        return "User=[empno="+empno+
                    ",ename="+ename+
                    ",job="+job+
                    ",mgr="+mgr+
                    ",hiredate="+hireDate+
                    ",sal="+sal+
                    ",comm="+comm+
                    ",deptno="+deptno+"]";     
    }
}

   MybatisTest.java

package com.lfy.main;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.lfy.bean.Emp;

/**
 * 使用log4j-1配置日志
 * @author lfy
 *
 */
public class MybatisTest {

    public static void main(String[] args) {

        //mybatis的配置文件
        String resource = "conf.xml";
        //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = MybatisTest.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
        //Reader reader = Resources.getResourceAsReader(resource); 
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();
        /**
         * 映射sql的标识字符串,
         * com.lfy.mapping.empMapper是empMapper.xml文件中mapper标签的namespace属性的值,
         * getEmp是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "com.lfy.mapping.empMapper.getEmp";//映射sql的标识字符串
        //执行查询返回一个唯一user对象的sql
        Emp emp = session.selectOne(statement, 7839);
        System.out.println(emp);
    }

}

   运行结果:

 Mybatis-第N篇配置log4j1、log4j2打印执行的sql语句

2、log4j2配置

   目录结构:

   Mybatis-第N篇配置log4j1、log4j2打印执行的sql语句

  conf.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>

    <settings>
       <!-- 配置用于控制台输出sql日志。低版本的mybatis不支持logImpl -->
       <setting name="logImpl" value="LOG4J2"/>
    </settings>
    
    <environments default="oracle">
        <environment id="oracle">
            <!-- 指定事务管理类型,type="JDBC"指直接使用JDBC的提交与回滚   -->
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
                <property name="username" value="scott" />
                <property name="password" value="12345" />
            </dataSource>
        </environment>
        <environment id="mysql">
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/world" />
                <property name="username" value="root" />
                <property name="password" value="12345" />
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <!-- 注册empMapper.xml文件-->
        <mapper resource="com/lfy/mapping/empMapper.xml"/>
    </mappers>
    
</configuration>

   log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <!--  <File name="File" fileName="../logs/test.log" append="true">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>  -->
    </appenders>

    <loggers>
        <logger name="com.lfy.mapping" level="debug" additivity="false">
            <appender-ref ref="Console"/>
        </logger>
        <!--  <logger name="log4j.logger.java.sql.Statement" level="info" additivity="false">
            <appender-ref ref="File"/>
        </logger>
        <Logger name="com.lfy.mapping" level="debug" additivity="false">
            <AppenderRef ref="File"/>
        </Logger>  -->

        <root level="info">
            <appender-ref ref="Console"/>
            <!--  <appender-ref ref="File"/> -->
        </root>
    </loggers>
</configuration>

  运行结果:

Mybatis-第N篇配置log4j1、log4j2打印执行的sql语句

  总结:

    使用log4j1时,需要编写引入log4j1的包、在conf.xml中添加<setting name="logImpl" value="LOG4J"/>、编写log4j.properties;

    使用log4j2时,需要引入log4j2的包、在conf.xml中添加<setting name="logImpl" value="LOG4J2"/>、编写log4j2.xml。

上一篇:java – 为什么Apache Kafka使用者不使用Log4j2根记录器?


下一篇:java – 如何以编程方式更改log4j2中的AppenderRef级别?