Teach you how to use SpringBoot logs

1. The role of logs

1.1 What are logs?

  Spring BootLogging refers to Spring Bootthe mechanism for recording events and information in an application. It is used to check BUG, ​​which can help us quickly locate and solve problems in the application.

What it does:

  • Help developers to debug: When there is a problem with the application, the developer can track and locate the problem according to the log information.
  • Know how your application is running: Logs can record various events and information about your application, such as application startup and shutdown, HTTP requests and responses, database operations, and more.
  • Maintain application stability: By setting an appropriate log level, excessive log information can be avoided from affecting application performance.
  • Follow security and compliance requirements: According to the security and compliance requirements of the application, some specific log information needs to be recorded, such as user login information, sensitive operation records, etc.

2. Custom log printing

  After creating a SpringBootproject, we click Run, and the following content will pop up in the console:

  These are actually the logs that come with the system. So how do we customize the log?

2.1 Get the log object

  


import org.slf4j.Logger; //必须导这个包
import org.slf4j.LoggerFactory;

@RestController
public class TestController {

    //1.得到日志对象(当前类的日志),
    private static final Logger log = LoggerFactory.getLogger(TestController.class);
    
    ......
    
    ......
}
复制代码

  There are several points to note. The first is that the log object Loggerpackage has a built-in log framework slf4j, which allows developers to use a consistent method to call different logging frameworks; second, generally each class has its own log File, method parameters are recommended as the current class, and this log file cannot be easily modified, so it is .Spring BootSlf4jAPIgetLoggerprivate static final

2.2 Make the object print the log

  LoggerProvides many methods for printing logs.

@ResponseBody //返回非静态页面
@Controller

public class TestController {

    //1.得到日志对象(当前类的日志)
    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @RequestMapping("/hi")
    public String Hi(){
        //打印日志的方法
        log.trace("我是trace");
        log.debug("我是debug");
        log.info("我是info");
        log.warn("我是warn");
        log.error("我是error");

        return "Hello World!";
    }
}
复制代码

  Let's run the program first:

  When we access this method (browser input path)

  You will see that the log will only appear after accessing this method, which can reflect the role of the log; since they are all printing logs, why are there so many methods? What does the printed content mean? I clearly wrote 5 methods, why only 3 were printed? Let’s answer one by one later:

2.3 Format of logs

  The output format of the log:

3. Log level

  Why did I clearly write 5 methods, why only printed 3? This is related to the log level.

3.1 Types of log levels

  SpringBootThe log level is used to control the verbosity of the output log.

  Each different log level corresponds to a different set of log information, the higher the level, the more detailed the output log information. The meanings of the various log levels are as follows:

  • 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, but needs attention;
  • error: error information, higher level error log information;
  • fatal: Fatal, the event that the program exits due to a code exception.

  SpringBootThe medium log levels from low to high are: trace < debug < info < warn < error < fatal, and the default level is info.

  Log output rules: the current level and the log higher than the current level can be output (fatal will not be output), and the above 5 different methods correspond to different log levels . Note that there is no fatal()method, because when fatalthe level appears, the program will be terminated.

  This is why 5 methods are written above and only 3 are printed.

3.2 Customize the level of the log

  We can set the log level in SpringBootthe configuration file application.properties:

# 自定义日志级别
logging.level.root=error
复制代码

  Now:

  The above is to set the level of the root path, and you can also set different directories at the same time.

# 自定义日志级别

# 对根目录设置
logging.level.root=error
# 对controller 目录设置一个级别
longing.level.com.example.demo.controller=trace  
# 它们不会冲突,除了 com.example.demo.controller 下为 trace,其它地方都为error。
复制代码

  The default log is DemoApplicationprinted in the startup class.

4. Persistence of logs

  Persistence is to put the log on the hard disk and store it as a log file. This step is very important.

4.1 Configuration file path

  Set the path to the configuration file in the configuration file:

# 设置日志文件的目录
logging.file.path=D:\\logging\\  
复制代码

  Instead of creating this path yourself, it will be created automatically, start running and access:

  It will create a file in the directory by default, which contains the log content written by yourself. So the question is, if I access the interface method many times, will it overwrite the content here?

  The answer is no, it will be appended later.

4.2 Configuration file name

  It can be further refined to the filename:

# 设置日志文件的文件名,注意这里是 name 属性
logging.file.name=D:\logging\mySpring.log
复制代码

  Now there is another problem. If the program runs for a long period of time (such as a production environment), there must be a lot of logs. It is obviously unrealistic to store it in one file, so how can it be automatically divided into multiple files?

  You can set the maximum capacity of the log file storage size.

# 设置日志大小的最大大小 1KB(一般不会这么小,这里用于演示)
logging.logback.rollingpolicy.max-file-size=1KB
复制代码

  This configuration item is used to specify the maximum size of a log file, and the supported units include KB, MB, GBand so on. , when the log file reaches the specified size, a new log file will be automatically created to continue recording log information. I will take the above code as an example. After multiple requests:

5. Output logs with lombok

  lombokIt is a framework, it can help us write get、setother methods, which is very convenient.

  Outputting logs with lombokis actually very simple, just add a comment:

@Controller
@ResponseBody
@Slf4j //加上这个注解,它会自己生成一个日志对象,对象名叫“log”,直接引用。
public class LogController {

    @RequestMapping("/hi")
    public String hi(){
        log.trace("我是trace");
        log.debug("我是debug");
        log.info("我是info");
        log.warn("我是warn");
        log.error("我是error");
        
        return "Hello World!";
    }
}
复制代码

Guess you like

Origin blog.csdn.net/ww2651071028/article/details/130551843