mybatis项目中添加logback日志

1、pom.xml

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>

        <!-- MySQL驱动 mybatis底层依赖jdbc驱动实现,本次不需要导入连接池,mybatis自带! -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--junit5测试-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- 日志 , 会自动传递slf4j门面-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
    </dependencies>

2、logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 指定日志输出的位置,ConsoleAppender表示输出到控制台 -->
    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 日志输出的格式 -->
            <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- 设置全局日志级别。日志级别按顺序分别是:TRACE、DEBUG、INFO、WARN、ERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
        <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>

    <!-- 根据特殊需求指定局部日志级别,可以是包名或全类名。 -->
    <logger name="com.atguigu.mybatis" level="DEBUG" />

</configuration>

3、建库建表

CREATE DATABASE `mybatis-example`;
 
USE `mybatis-example`;
 
CREATE TABLE `t_emp`(
  emp_id INT AUTO_INCREMENT,
  emp_name CHAR(100),
  emp_salary DOUBLE(10,5),
  PRIMARY KEY(emp_id)
);
 
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);

4、Employee.java

package com.atguigu.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private Integer empId;
    private String empName;
    private Double empSalary;
}

5、mybatis-config.xml(mybatis的总配置文件)

<?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>
 
    <!-- environments表示配置Mybatis的开发环境,可以配置多个环境,在众多具体环境中,使用default属性指定实际运行时使用的环境。default属性的取值是environment标签的id属性的值。 -->
    <environments default="development">
        <!-- environment表示配置Mybatis的一个具体的环境 -->
        <environment id="development">
            <!-- Mybatis的内置的事务管理器 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源 -->
            <dataSource type="POOLED">
                <!-- 建立数据库连接的具体信息 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
 
    <mappers>
        <!-- Mapper注册:指定Mybatis映射文件的具体位置 -->
        <!-- mapper标签:配置一个具体的Mapper映射文件 -->
        <!-- resource属性:指定Mapper映射文件的实际存储位置,这里需要使用一个以类路径根目录为基准的相对路径 -->
        <!--    对Maven工程的目录结构来说,resources目录下的内容会直接放入类路径,所以这里我们可以以resources目录为基准 -->
        <mapper resource="mapper/EmpMapper.xml"/>
    </mappers>
 
</configuration>

6、MybatisTest.java

package com.atguigu.mybatis;
import com.atguigu.mybatis.mapper.EmpMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
 
    SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;
    EmpMapper empMapper;
 
    @BeforeEach
    public void setup() throws IOException {
        // 获取资源流,读取"mybatis-config.xml"文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 使用资源流创建SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 使用SqlSessionFactory打开一个Session
        sqlSession = sqlSessionFactory.openSession();
        // 使用Session获取EmpMapper的Mapper对象
        empMapper = sqlSession.getMapper(EmpMapper.class);
    }
 
 
    // 在每个测试用例之后执行的清理方法
    @AfterEach
    public void teardown() {
        sqlSession.close();  // 关闭SqlSession
    }
 
 
    @Test
    public void getEmployeeListTest() {
        empMapper.getEmployeeList().forEach(System.out::println);
    }
    //Employee(empId=1, empName=tom, empSalary=200.33)
    //Employee(empId=2, empName=jerry, empSalary=666.66)
    //Employee(empId=3, empName=andy, empSalary=777.77)
 
    @Test
    public void getEmployeeByIdTest() throws IOException {
        System.out.println(empMapper.getEmployeeById(1));
        //Employee(empId=1, empName=tom, empSalary=200.33)
    }
}
D:\Java\jdk-17\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar=18702:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\develop\maven\repository\org\junit\platform\junit-platform-launcher\1.3.1\junit-platform-launcher-1.3.1.jar;D:\develop\maven\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;D:\develop\maven\repository\org\junit\platform\junit-platform-engine\1.3.1\junit-platform-engine-1.3.1.jar;D:\develop\maven\repository\org\junit\platform\junit-platform-commons\1.3.1\junit-platform-commons-1.3.1.jar;D:\develop\maven\repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;D:\develop\maven\repository\org\junit\jupiter\junit-jupiter-engine\5.3.1\junit-jupiter-engine-5.3.1.jar;D:\develop\maven\repository\org\junit\jupiter\junit-jupiter-api\5.3.1\junit-jupiter-api-5.3.1.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\plugins\junit\lib\junit5-rt.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\plugins\junit\lib\junit-rt.jar;F:\IdeaProjects\workspace\pro-ssm\pro18-mybatis-begin\target\test-classes;F:\IdeaProjects\workspace\pro-ssm\pro18-mybatis-begin\target\classes;F:\my_java\maven_repository\org\mybatis\mybatis\3.5.11\mybatis-3.5.11.jar;F:\my_java\maven_repository\mysql\mysql-connector-java\8.0.25\mysql-connector-java-8.0.25.jar;F:\my_java\maven_repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar;F:\my_java\maven_repository\org\junit\jupiter\junit-jupiter-api\5.3.1\junit-jupiter-api-5.3.1.jar;F:\my_java\maven_repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;F:\my_java\maven_repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;F:\my_java\maven_repository\org\junit\platform\junit-platform-commons\1.3.1\junit-platform-commons-1.3.1.jar;F:\my_java\maven_repository\org\projectlombok\lombok\1.18.20\lombok-1.18.20.jar;F:\my_java\maven_repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;F:\my_java\maven_repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;F:\my_java\maven_repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit5 com.atguigu.mybatis.MybatisTest,getEmployeeListTest
19:39:19,463 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
19:39:19,463 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
19:39:19,463 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/F:/IdeaProjects/workspace/pro-ssm/pro18-mybatis-begin/target/classes/logback.xml]
19:39:19,537 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
19:39:19,540 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
19:39:19,548 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
19:39:19,575 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
19:39:19,575 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
19:39:19,576 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.atguigu.mybatis] to DEBUG
19:39:19,576 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
19:39:19,577 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@62230c58 - Registering current configuration as safe fallback point
[19:39:19.582] [DEBUG] [main] [org.apache.ibatis.logging.LogFactory] [Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.]
[19:39:19.596] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:39:19.596] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:39:19.596] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:39:19.596] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:39:19.682] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Opening JDBC Connection]
[19:39:20.235] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Created connection 1193398802.]
[19:39:20.236] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4721d212]]
[19:39:20.239] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.getEmployeeList] [==>  Preparing: select emp_id empId, emp_name empName, emp_salary empSalary from t_emp]
[19:39:20.280] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.getEmployeeList] [==> Parameters: ]
[19:39:20.320] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.getEmployeeList] [<==      Total: 3]
Employee(empId=1, empName=tom, empSalary=200.33)
Employee(empId=2, empName=jerry, empSalary=666.66)
Employee(empId=3, empName=andy, empSalary=777.77)
[19:39:20.325] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4721d212]]
[19:39:20.326] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4721d212]]
[19:39:20.326] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Returned connection 1193398802 to pool.]

Process finished with exit code 0
D:\Java\jdk-17\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar=18726:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\develop\maven\repository\org\junit\platform\junit-platform-launcher\1.3.1\junit-platform-launcher-1.3.1.jar;D:\develop\maven\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;D:\develop\maven\repository\org\junit\platform\junit-platform-engine\1.3.1\junit-platform-engine-1.3.1.jar;D:\develop\maven\repository\org\junit\platform\junit-platform-commons\1.3.1\junit-platform-commons-1.3.1.jar;D:\develop\maven\repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;D:\develop\maven\repository\org\junit\jupiter\junit-jupiter-engine\5.3.1\junit-jupiter-engine-5.3.1.jar;D:\develop\maven\repository\org\junit\jupiter\junit-jupiter-api\5.3.1\junit-jupiter-api-5.3.1.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\plugins\junit\lib\junit5-rt.jar;D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\plugins\junit\lib\junit-rt.jar;F:\IdeaProjects\workspace\pro-ssm\pro18-mybatis-begin\target\test-classes;F:\IdeaProjects\workspace\pro-ssm\pro18-mybatis-begin\target\classes;F:\my_java\maven_repository\org\mybatis\mybatis\3.5.11\mybatis-3.5.11.jar;F:\my_java\maven_repository\mysql\mysql-connector-java\8.0.25\mysql-connector-java-8.0.25.jar;F:\my_java\maven_repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar;F:\my_java\maven_repository\org\junit\jupiter\junit-jupiter-api\5.3.1\junit-jupiter-api-5.3.1.jar;F:\my_java\maven_repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;F:\my_java\maven_repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;F:\my_java\maven_repository\org\junit\platform\junit-platform-commons\1.3.1\junit-platform-commons-1.3.1.jar;F:\my_java\maven_repository\org\projectlombok\lombok\1.18.20\lombok-1.18.20.jar;F:\my_java\maven_repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;F:\my_java\maven_repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;F:\my_java\maven_repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit5 com.atguigu.mybatis.MybatisTest,getEmployeeByIdTest
19:40:00,097 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
19:40:00,097 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
19:40:00,097 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/F:/IdeaProjects/workspace/pro-ssm/pro18-mybatis-begin/target/classes/logback.xml]
19:40:00,180 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
19:40:00,184 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]
19:40:00,190 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
19:40:00,218 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG
19:40:00,219 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
19:40:00,220 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [com.atguigu.mybatis] to DEBUG
19:40:00,220 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
19:40:00,221 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@62230c58 - Registering current configuration as safe fallback point
[19:40:00.226] [DEBUG] [main] [org.apache.ibatis.logging.LogFactory] [Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.]
[19:40:00.242] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:40:00.242] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:40:00.242] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:40:00.242] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [PooledDataSource forcefully closed/removed all connections.]
[19:40:00.316] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Opening JDBC Connection]
[19:40:00.869] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Created connection 1626852381.]
[19:40:00.870] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@60f7cc1d]]
[19:40:00.874] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.getEmployeeById] [==>  Preparing: select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_id = ?]
[19:40:00.918] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.getEmployeeById] [==> Parameters: 1(Integer)]
[19:40:00.961] [DEBUG] [main] [com.atguigu.mybatis.mapper.EmpMapper.getEmployeeById] [<==      Total: 1]
Employee(empId=1, empName=tom, empSalary=200.33)
[19:40:00.965] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@60f7cc1d]]
[19:40:00.966] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@60f7cc1d]]
[19:40:00.966] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Returned connection 1626852381 to pool.]

Process finished with exit code 0

 

 7、SLF4J

     SLF4J,即 简单日志门面Simple Logging Facade for Java),不是具体的日志解决方案,它只服务于各种各样的日志系统。按照官方的说法,SLF4J是一个用于日志系统的简单Facade,允许最终用户在部署其应用时使用其所希望的日志系统。实际上,SLF4J所提供的核心API是一些接口以及一个LoggerFactory的工厂类。

     使用SLF4J的时候,不需要在代码中或配置文件中指定你打算使用那个具体的日志系统。如同使用JDBC基本不用考虑具体数据库一样,SLF4J提供了统一的记录日志的接口,只要按照其提供的方法记录即可,最终日志的格式、记录级别、输出方式等通过具体日志系统的配置来实现,因此可以在应用中灵活切换日志系统。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值