How to use SpringBoot log?

1. The role of logs

1.1 What is a log?

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

What it does:

  • Help developers debug: When an application has a problem, developers can track and locate the problem based on log information.
  • Understand the running status of the application: Logs can record various events and information of the application, such as application startup and shutdown, HTTP requests and responses, database operations, etc.
  • Maintain application stability: By setting appropriate log levels, you can prevent excessive log information from affecting application performance.
  • Comply with 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. Customized 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 a few points to note. The first is that the log object Loggerpackage   has a log framework built into it  slf4j, which allows developers to call different logging frameworks consistently; second, generally each class has its own log. File and method parameters are recommended for the current class, and this log file cannot be easily modified, so it is .Spring BootSlf4jAPIgetLoggerprivate static final

2.2 Make the object print logs

  Logger Provides 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. This can reflect the role of the log; since they are all about printing logs, why are so many methods provided? What does the printed content mean? I clearly wrote 5 methods, why only 3 were printed? I will answer them one by one later:

2.3 Log format

  Log output format:

3. Log level

  Why did I only print 3 of the 5 methods I wrote? 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 log information output. The meanings of the various log levels are as follows:

  • trace: trace, meaning a little, the lowest level;
  • debug: Print key information when debugging is needed;
  • info: ordinary printing information (default log level);
  • warn: Warning, does not affect use, but requires attention;
  • error: error message, higher-level error log information;
  • fatal: Fatal, an event that causes the program to exit execution due to code exceptions.

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

  Log output rules: Only the current level and logs higher than the current level can be output (fatal will not be output). 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 there are 5 methods written above, but only 3 are printed.

3.2 Customize the log level

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

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

  Now:

  The above is to set the level for the root path, and it can also be set for 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. Log persistence

  Persistence means placing the log on the hard disk and storing 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\\  
复制代码

  You don’t have to create 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 you wrote yourself. So the question is, if I access the interface method multiple times, will it overwrite the content?

  The answer is no, it will be appended later.

4.2 Configuration file name

  You can further refine it to the file name:

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

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

  You can set the maximum capacity for 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. Supported units include  KB, MB, GB etc. , when the log file reaches the specified size, a new log file will be automatically created to continue recording log information. I take the above code as an example. After multiple requests:

5. Use lombok to output logs

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

  Using  lombok the output log is actually very simple, just add an annotation:

@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/2301_76607156/article/details/130557912