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

1、pom.xml

    <dependencies>
        <dependency>
            &lt;groupId&gt;org.mybatis</groupId&gt;
            <artifactId&gt;mybatis</artifactId&gt;
        </dependency&gt;

        <!-- MySQL驱动 mybatis底层依赖jdbc驱动实现,本次不需要导入连接池,mybatis自带! --&gt;
        <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、mybatisconfig.xmlmybatis的总配置文件

<?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:Javajdk-17binjava.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2libidea_rt.jar=18702:D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2bin" -Dfile.encoding=UTF-8 -classpath "D:developmavenrepositoryorgjunitplatformjunit-platform-launcher1.3.1junit-platform-launcher-1.3.1.jar;D:developmavenrepositoryorgapiguardianapiguardian-api1.0.0apiguardian-api-1.0.0.jar;D:developmavenrepositoryorgjunitplatformjunit-platform-engine1.3.1junit-platform-engine-1.3.1.jar;D:developmavenrepositoryorgjunitplatformjunit-platform-commons1.3.1junit-platform-commons-1.3.1.jar;D:developmavenrepositoryorgopentest4jopentest4j1.1.1opentest4j-1.1.1.jar;D:developmavenrepositoryorgjunitjupiterjunit-jupiter-engine5.3.1junit-jupiter-engine-5.3.1.jar;D:developmavenrepositoryorgjunitjupiterjunit-jupiter-api5.3.1junit-jupiter-api-5.3.1.jar;D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2libidea_rt.jar;D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2pluginsjunitlibjunit5-rt.jar;D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2pluginsjunitlibjunit-rt.jar;F:IdeaProjectsworkspacepro-ssmpro18-mybatis-begintargettest-classes;F:IdeaProjectsworkspacepro-ssmpro18-mybatis-begintargetclasses;F:my_javamaven_repositoryorgmybatismybatis3.5.11mybatis-3.5.11.jar;F:my_javamaven_repositorymysqlmysql-connector-java8.0.25mysql-connector-java-8.0.25.jar;F:my_javamaven_repositorycomgoogleprotobufprotobuf-java3.11.4protobuf-java-3.11.4.jar;F:my_javamaven_repositoryorgjunitjupiterjunit-jupiter-api5.3.1junit-jupiter-api-5.3.1.jar;F:my_javamaven_repositoryorgapiguardianapiguardian-api1.0.0apiguardian-api-1.0.0.jar;F:my_javamaven_repositoryorgopentest4jopentest4j1.1.1opentest4j-1.1.1.jar;F:my_javamaven_repositoryorgjunitplatformjunit-platform-commons1.3.1junit-platform-commons-1.3.1.jar;F:my_javamaven_repositoryorgprojectlomboklombok1.18.20lombok-1.18.20.jar;F:my_javamaven_repositorychqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;F:my_javamaven_repositorychqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;F:my_javamaven_repositoryorgslf4jslf4j-api1.7.25slf4j-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:Javajdk-17binjava.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2libidea_rt.jar=18726:D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2bin" -Dfile.encoding=UTF-8 -classpath "D:developmavenrepositoryorgjunitplatformjunit-platform-launcher1.3.1junit-platform-launcher-1.3.1.jar;D:developmavenrepositoryorgapiguardianapiguardian-api1.0.0apiguardian-api-1.0.0.jar;D:developmavenrepositoryorgjunitplatformjunit-platform-engine1.3.1junit-platform-engine-1.3.1.jar;D:developmavenrepositoryorgjunitplatformjunit-platform-commons1.3.1junit-platform-commons-1.3.1.jar;D:developmavenrepositoryorgopentest4jopentest4j1.1.1opentest4j-1.1.1.jar;D:developmavenrepositoryorgjunitjupiterjunit-jupiter-engine5.3.1junit-jupiter-engine-5.3.1.jar;D:developmavenrepositoryorgjunitjupiterjunit-jupiter-api5.3.1junit-jupiter-api-5.3.1.jar;D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2libidea_rt.jar;D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2pluginsjunitlibjunit5-rt.jar;D:BaiduNetdiskDownloadIntelliJ IDEA 2023.2pluginsjunitlibjunit-rt.jar;F:IdeaProjectsworkspacepro-ssmpro18-mybatis-begintargettest-classes;F:IdeaProjectsworkspacepro-ssmpro18-mybatis-begintargetclasses;F:my_javamaven_repositoryorgmybatismybatis3.5.11mybatis-3.5.11.jar;F:my_javamaven_repositorymysqlmysql-connector-java8.0.25mysql-connector-java-8.0.25.jar;F:my_javamaven_repositorycomgoogleprotobufprotobuf-java3.11.4protobuf-java-3.11.4.jar;F:my_javamaven_repositoryorgjunitjupiterjunit-jupiter-api5.3.1junit-jupiter-api-5.3.1.jar;F:my_javamaven_repositoryorgapiguardianapiguardian-api1.0.0apiguardian-api-1.0.0.jar;F:my_javamaven_repositoryorgopentest4jopentest4j1.1.1opentest4j-1.1.1.jar;F:my_javamaven_repositoryorgjunitplatformjunit-platform-commons1.3.1junit-platform-commons-1.3.1.jar;F:my_javamaven_repositoryorgprojectlomboklombok1.18.20lombok-1.18.20.jar;F:my_javamaven_repositorychqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;F:my_javamaven_repositorychqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;F:my_javamaven_repositoryorgslf4jslf4j-api1.7.25slf4j-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提供了统一记录日志的接口,只要按照其提供的方法记录即可,最终日志的格式记录级别、输出方式通过具体日志系统的配置来实现,因此可以应用中灵活切换日志系统。

原文地址:https://blog.csdn.net/m0_65152767/article/details/134697456

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_47156.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注