六、日志系统

时间:2021-6-4 作者:qvyue

二、具体操作

2.1 初始状态

Spring使用commons-logging日志包。打印的日志是下面这样的。不用细看,截图放在这是为了和后面日志打印的情况对比。

六、日志系统
image.png

2.2 加入 slf4j+logback

六、日志系统
image.png
        
        org.slf4jslf4j-apich.qos.logbacklogback-classic

代码不变,日志情况如下:

六、日志系统
image.png

2.3 我们主动打印的日志

把查询到的Admin对象以日志的方式打印出来,代码如下

package com.atguigu.crowd.test;

import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.mapper.AdminMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

// 指定 Spring 给 Junit 提供的运行器类
@RunWith(SpringJUnit4ClassRunner.class)
// 加载 Spring 配置文件的注解
@ContextConfiguration(locations = {"classpath:spring-persist-mybatis.xml"})
public class CrowdSpringTest {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private AdminMapper adminMapper;
    @Test
    public void testLog() {

        // 1.获取Logger对象,这里传入的Class对象就是当前打印日志的类
        Logger logger = LoggerFactory.getLogger(CrowdSpringTest.class);

        // 2.按照 Debug 级别打印日志
        Admin admin = adminMapper.selectByPrimaryKey(2);
        logger.debug(admin.toString());
    }
    @Test
    public void testAdminMapperAutowired() {
        Admin admin = new Admin(null,"zhangsan","123123","张三","zhangsan@163.com",null);
        int count = adminMapper.insert(admin);

        // 如果在实际开发中,所有想查看数值的地方都使用sysout方式打印,会给项目上线运行带来问题!
        // sysout本质上是一个IO操作,通常IO的操作是比较消耗性能的。如果项目中sysout很多,那么对性能的影响就比较大了。
        // 即使上线前专门花时间删除代码中的sysout,也很可能有遗漏,而且非常麻烦。
        // 而如果使用日志系统,那么通过日志级别就可以批量的控制信息的打印。
        System.out.println("受影响的行数:"+count);
    }
    @Test
    public void testDataSource() throws SQLException {
        // 1.通过数据源对象获取数据源连接
        Connection connection = dataSource.getConnection();
        // 2.打印数据库连接
        System.out.println(connection);
    }
}
六、日志系统
image.png

这里我们看到除了 Druid 数据源打印了两条日志,Spring 和 MyBatis 并没有通
过 slf4j 打印日志。所以下一步我们要考虑的就是如何将框架所使用的日志系统统一到 slf4j。

2.4 更换框架的日志系统

排除 commons-logging
../atcrowdfunding01-admin-parent/atcrowdfunding02-admin-webui/pom.xml

        
        org.springframeworkspring-testtestcommons-loggingcommons-logging

../atcrowdfunding01-admin-parent/atcrowdfunding03-admin-component/pom.xml

       org.springframeworkspring-ormcommons-loggingcommons-logging

加入转换包
../atcrowdfunding01-admin-parent/atcrowdfunding03-admin-component/pom.xml

        
        org.slf4jjcl-over-slf4j

打印效果局部:

六、日志系统
image.png

2.5 logback 配置文件

logback 工作时的具体细节可以通过 logback.xml 来配置。

六、日志系统
image.png
[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n
六、日志系统
image.png
声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:qvyue@qq.com 进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。