spring boot log file

The role of the log

The log is an important part of the program. If the program reports an error, we need to check the log to find the cause of the error.

  • Record error logs and warning logs to facilitate later discovery and location of program problems
  • Record user login logs to facilitate analysis of whether users log in normally or maliciously crack users
  • Record the operation log of the system to facilitate data recovery and locate the operator
  • Record the execution time of the program to provide support for future optimization programs

How to use the log

  • Spring boot has a built-in logging framework SLF4J + logback
  • The default output log is not defined and printed by the developer. How can the developer customize the printed log?
  • The log is printed on the console by default and cannot be saved. How to save the log permanently.

Description of common logging frameworks
insert image description here

Custom log printing

  1. Get the log object in the program
  2. Use the method provided by the log object to print the log

1. Get the log object in the program

A log object can only belong to one class, and each class has its own unique log, so it should be modified with private, it should be static, and finally it does not want to be changed elsewhere.

import org.slf4j.Logger;

private static final Logger log = LoggerFactory.getLogger(TestController.class);

Be careful not to choose wrong
insert image description hereinsert image description here

2. Use the method provided by the log object to print the log

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
public class TestController {
    
    
    //1. 得到日志对象
    //一个日志对象只会属于一个类,每个类都有自己独有的日志,因此应该用 private 修饰,应该是静态的,不希望在其他地方被改变的
    private static final Logger log = LoggerFactory.getLogger(TestController.class);


    @RequestMapping("/sayHi")   // = @WebServlet("/url") localhost:8080/sayHi
    public String sayHi() {
    
    
        // 打印日志
        log.trace("i an trace");  //所有级别都打印
        log.debug("i am debug");  //打印调试级别
        log.info("i am info");
        log.warn("i am warn");
        log.error("i am error");
        return "hello world";  //默认返回名为hello world的页面,
    }
}

log format

insert image description here
insert image description here

log level

The log level can help us filter out important information.
Can control different logs required in different environments

log level:

  • trace: trace, a little meaning, the lowest level
  • debug: Print key information when debugging is required
  • info: common print information (default log level)
  • warn: warning, does not affect the use
  • error: error information, higher level error log information
  • fatal: Fatal, because the code exception causes the program to exit execution, the highest level, there is no way to call

trace < debug < info < warn < error < fatal

If warn is set, only logs of warn, error, and fatal levels can be received. Anything below warn will not be output.

level setting

Just set the logging.level configuration item in the configuration file. For
other files, set the log level to error, and set the log level to trace under com.example.demo

# 日志级别设置
# 非常灵活,可以精确到某一个文件夹
logging:
  level:
    root: error
    com: 
      example: 
        demo: trace

log persistence

The above logs are all output on the console. In the production environment, the logs need to be saved, that is, persisted.
If you want to persist the log, you only need to specify the log storage directory in the configuration file or specify the log save file name, and Spring Boot will write the console log to the corresponding directory or file.

The method of spring boot log persistence (save log)

  • Set the save path of the log or
  • Set the save name of the log

Set the save path of the log

# 日志保存路径
#  1. 尽量不要将保存的日志放在系统盘(C盘)
#  2. 路径中不要出现中文和空格
logging:
  file:
    path: E:\\java\\java-learning\\5.EE\\

insert image description here
Once the log file is generated, the log file and its content will be permanently saved, and the file and content will not be lost due to restarting or stopping the project

Set the save name of the log.
If you don’t set the address and only write the name, it will be placed under the path of the project.

logging:
  file:
    name: E:\\java\\java-learning\\5.EE\\spring-1.log

Production-level log classification: the specifics still need to be determined according to the business scenario

  1. Program running log (stored in a file)

  2. The default maximum size of the business log (stored in the database) is 10MB (you can also set it yourself). When the maximum size is exceeded, a new log file will be created for storage.

Simpler log output: lombok

  1. Add lombok framework support
  2. Use the @Slf4j annotation to output logs
package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j   //给当前类中添加一个叫做 log 的日志对象(就是 Slf4j 里面提供的 logger)
public class LoginController {
    
    
    @RequestMapping("/log/sayHi")
    public String sayHi() {
    
    
        log.error("this is Slf4j log error");
        log.info("this is Slf4j log info");
        return "login sayHi";
    }
}

lombok More annotations

Basic annotation

annotation effect
@Getter Automatically add getter methods
@Setter Automatically add setter methods
@ToString Automatically add toString method
@EqualsAndHashCode Automatically add equals and hashCode methods
@NoArgsConstructor Automatically add no-argument constructor
@AllArgsConstructor Automatically add all-attribute construction methods, the order is in accordance with the definition order of the attributes
@NonNull Property cannot be null
@RequiredArgsConstructor A constructor that automatically adds required attributes, final+ @NonNull attributes are required

Combining annotations

annotation effect
@Data @Getter + @Setter + @ToString + @EqualsAndHashCode + @RequiredArgsConstructor + @NoArgsConstructor

Explanation of lombok principle

Java program running principle
insert image description here
Lombok function
insert image description here
Lombok is not a runtime framework, but a compile-time framework.
Lombok generates bytecodes from Java code corresponding to Lombok annotations when Java code is converted into class code.

View the LoginController under the target
insert image description here

Guess you like

Origin blog.csdn.net/weixin_44431128/article/details/130392121