SpringBoot集成logback日志—日志配置文件—@Slf4j注解的使用

SpringBoot集成logback日志

  • SpringBoot集成logback日志
    • 使用该功能的步骤:
    • 1. 创建SpringBoot框架web项目
    • 2. 添加依赖
    • 3. 核心配置文件
    • 4. 手动指定资源文件夹
    • 5. 编写控制层,业务逻辑层,持久层
      • 5.1 控制层——添加@Slf4j注解
      • 5.2 业务逻辑层
      • 5.3 持久层
    • 6. 日志文件
    • 7. Application启动类
    • 8. 启动测试
      • 8.1 root日志级别低于追加器
      • 8.2 root日志级别高于追加器
      • 8.3 root日志级别低于追加器

SpringBoot集成logback日志

Spring Boot 默认使用Logback记录日志
Spring Boot starter 都会默认引入spring-boot-starter-logging,不需要再引入
日志级别从高到低分为:TRACE < DEBUG < INFO < WARN < ERROR < FATAL
如果设置为 WARN ,则低于 WARN 的信息都不会输出。
Spring Boot中默认配置ERROR、WARN和INFO级别的日志输出到控制台。

使用该功能的步骤:

  1. 创建SpringBoot框架web项目
  2. 添加依赖
  3. 核心配置文件
  4. 手动指定资源文件夹
  5. 编写控制层,业务逻辑层,持久层
  6. 日志文件
  7. Application启动类
  8. 启动测试

1. 创建SpringBoot框架web项目

2. 添加依赖

src/main/resources/logback-spring.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.7.RELEASEversion>
        <relativePath/>
    parent>
    <groupId>com.guo.springbootgroupId>
    <artifactId>springboot-logbackartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.1version>
        dependency>
        <dependency>
            <groupId>com.h2databasegroupId>
            <artifactId>h2artifactId>
            <scope>runtimescope>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
        plugins>
    build>
project>

3. 核心配置文件

src/main/resources/application.properties

# 应用名称
server.servlet.context-path=/
# 应用服务 WEB 访问端口
server.port=8079
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.type=com.zaxxer.hikari.HikariDataSource

4. 手动指定资源文件夹

默认情况下,Mybatis 的 xml 映射文件不会编译到 target 的 class 目录下,所以我们需要在 pom.xml 文件中配置 resource。

本次程序引入依赖是Mybatis-Plus,不需要xml映射文件,,所以可以省略这一步

<build>
   
    <resources>
        <resource>
            <directory>src/main/javadirectory>
            <includes>
                <include>**/*.xmlinclude>
            includes>
        resource>
    resources>
    
    <plugins>
        <plugin>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-maven-pluginartifactId>
        plugin>
    plugins>
build>

5. 编写控制层,业务逻辑层,持久层

5.1 控制层——添加@Slf4j注解

在类上添加@Slf4j注解,在方法中直接使用log.xxx();

src/main/java/com/guo/springboot/controller/StudentController.java

package com.guo.springboot.controller;
import com.guo.springboot.model.Student;
import com.guo.springboot.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Slf4j
public class StudentController {
    @Autowired
    private StudentService studentService;
//    log.info("查询当前学生总人数");

    @GetMapping("/student/count")
    public @ResponseBody Object studentCount(){
        int i = studentService.queryStudentCount();
        log.trace("查询学生人数trace");
        log.debug("查询学生人数debug");
        log.info("查询学生人数info");
        log.warn("查询学生人数warn");
        log.error("查询学生人数error");
        return "学生人数为"+i;
    }
    @RequestMapping("/student/detail")
    public @ResponseBody Object student(Integer id){
        Student student = studentService.queryStudentById(id);
        return student;
    }
    @RequestMapping("/student")
    public @ResponseBody Object student1(){
        return studentService.queryStudentList();
    }
}

5.2 业务逻辑层

  1. 接口

src/main/java/com/guo/springboot/service/StudentService.java

package com.guo.springboot.service;
import com.guo.springboot.model.Student;
import java.util.List;
public interface StudentService {
    Integer queryStudentCount();
    Student queryStudentById(Integer id);
    List<Student> queryStudentList();
}
  1. 映射接口

src/main/java/com/guo/springboot/mapper/StudentMapper.java

package com.guo.springboot.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.guo.springboot.model.Student;
public interface StudentMapper extends BaseMapper<Student> {
}
  1. 接口实现类

src/main/java/com/guo/springboot/service/impl/StudentServiceImpl.java

package com.guo.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guo.springboot.mapper.StudentMapper;
import com.guo.springboot.model.Student;
import com.guo.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public Integer queryStudentCount() {
        QueryWrapper<Student> queryWrapper=new QueryWrapper();
        Long aLong = studentMapper.selectCount(queryWrapper);
        int num = Math.toIntExact(aLong);
        return num;
    }
    @Override
    public Student queryStudentById(Integer id) {
        Student student = studentMapper.selectById(id);
        return student;
    }
    @Override
    public List<Student> queryStudentList() {
        return studentMapper.selectList(null);
    }
}

5.3 持久层

src/main/java/com/guo/springboot/model/Student.java

package com.guo.springboot.model;
public class Student {
  private Integer id;
  private String name;
  private String sex;
  private Integer age;
  public Integer getId() {
    return id;
  }
  public void setId(Integer id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getSex() {
    return sex;
  }
  public void setSex(String sex) {
    this.sex = sex;
  }
  public Integer getAge() {
    return age;
  }
  public void setAge(Integer age) {
    this.age = age;
  }
}

6. 日志文件

Spring Boot官方推荐优先使用带有-spring 的文件名作为你的日志配置(如使用logback-spring.xml ,而不是logback.xml),命名为logback-spring.xml的日志配置文件。默认的命名规则,并且放在 src/main/resources 下如果你即想完全掌控日志配置,但又不想用logback.xml作为Logback配置的名字,application.yml可以通过logging.config属性指定自定义的名字:

logging.config=classpath:logging-config.xml

SpringBoot集成logback日志—日志配置文件—@Slf4j注解的使用_第1张图片

logback-spring.xml





<configuration scan="true" scanPeriod="10 seconds">
    
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>infolevel>
        filter>
        <encoder>
            <Pattern>>%date %5p [%thread] %logger{60} [%file :  %line] %msg%nPattern>
            
            <charset>UTF-8charset>
        encoder>
    appender>

    
    
    <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <file>D:\myDev\log\debug.logfile>
        
        <encoder>
            <pattern>%date %5p [%thread] %logger{60} [%file :  %line] %msg%npattern>
            <charset>UTF-8charset> 
        encoder>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            
            <fileNamePattern>D:\myDev\log\debug-%d{yyyy-MM-dd}.%i.logfileNamePattern>
            
            <maxHistory>30maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>
        rollingPolicy>
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debuglevel>
            <onMatch>ACCEPTonMatch>
            <onMismatch>DENYonMismatch>
        filter>
    appender>

    
    <logger name="com.guo.springboot.mapper" level="DEBUG"/>
    
    
    <root level="debug">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="DEBUG_FILE"/>    
    root>
configuration>

7. Application启动类

package com.guo.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.guo.springboot.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

8. 启动测试

8.1 root日志级别低于追加器

root :< root level=“debug”>
追加器: info
日志打印:日志级别:info

SpringBoot集成logback日志—日志配置文件—@Slf4j注解的使用_第2张图片

8.2 root日志级别高于追加器

root :< root level=“info”>
追加器: debug
日志打印:日志级别:info

SpringBoot集成logback日志—日志配置文件—@Slf4j注解的使用_第3张图片

8.3 root日志级别低于追加器

root :< root level=“info”>
追加器: error
日志打印:日志级别:error
SpringBoot集成logback日志—日志配置文件—@Slf4j注解的使用_第4张图片

你可能感兴趣的:(Spring,Boot,spring,boot,logback,mybatis)