The role, classification, format and persistence of SpringBoot~log, analysis of lombok principle

The role of the log

The log records the time, location, status and other related information of the system behavior, which can help us understand and monitor the system status , and can remind us to deal with it in time when an error occurs or is approaching a certain dangerous state. Locate and diagnose problems.

custom log

When SpringBoot starts and runs, log information is output in the console:
insert image description here
these logs are already defined in Spring, not developer-defined logs.
If you want to output a custom log, you need the following steps:
1. Get the log object in the program
2. Use the log object to output the content

Get the log object:

private static Logger logger= LoggerFactory.getLogger(UserController.class);

Use the log object to output content:

  //2.使用日志对象输出信息
  logger.info("这是日志记录的信息");

output:

这是日志记录的信息

The Logger used here is under the package, because the logging framework slf4jis built-in in SpringBoot , which can be called directly to output the log.slf4jslf4j
insert image description here

Common logging frameworks

There are two framework modes for logging, one is the facade mode and the other is the implementation mode .
The facade mode is also called the appearance mode ( Facade), which can be understood as a layer of encapsulation. It encapsulates the internal subsystem implementation and provides a unified interface to the outside world, thereby shielding the differences in the use of the subsystems and greatly reducing the difficulty of using the system. , while improving the maintainability and scalability of the system.
What really works is the implementation of the subsystem, and the external facade framework is more like a service worker, which only plays a docking role.

There are two common facades: JCL (commons-logging) and SLF4j .
Common implementation frameworks are log4j1/2, jul, logback .
As shown below:
insert image description here

The bottom layer of SpringBoot is Spring. The default logging framework used by Spring is the JCL facade, while the logging framework used by SpringBoot is the SLF4J facade and logback to implement logging.

springBoot underlying dependencies:
insert image description here

log level

  • TRACE : Ordinary trace logs, the lowest level log information.
  • DEBUG : log information when debugging. The logs at the TRACE and DEBUG levels are mainly to record the running status of each step of the system accurately . Through this record, you can view the execution of each step of an operation, and you can pinpoint the problem.
  • INFO : Ordinary log information, record the state of the normal operation of the system, the default level of the log
  • WARN : Warning log, the problem does not affect the use, but needs attention.
  • ERROR : Error information, higher-level error log information. Errors of this level require immediate manual intervention, but the urgency is lower than fatal. Both ERROR and FATAL are the server's own exceptions, such as the user's own improper operation, etc., should not be recorded as ERROR logs.
  • FATAL : Fatal errors, the highest log level, indicating system-level errors that need to be handled immediately . When this error occurs, it means that the service has become unavailable, or it can be said that the service is down, and the technician needs to intervene immediately. In general, a fatal-level log should be recorded only once in the life cycle of a process, that is, when the process encounters an unrecoverable error and exits execution.

Level:
IOFO is the default log level , we can set the log level in the code, and logs below the set level will be ignored (not displayed).
insert image description here
Log level settings:

# 日志级别设置
logging:
   level:
     root: info

log format

insert image description here

log persistence

The log will not be output on the console, but the log will be saved so that it can be traced back when a problem occurs. This process is called persistence.

There are two ways to set log persistence:
1. Set the log storage path:
SpringBoot will generate log files in its own format and save them in the corresponding directory.

# 日志持久化保存
logging:
  file:
    path: C:\logs\
  level:
    root: info

After starting SpringBoot, log files will appear in the logs directory of the C drive
insert image description here

2. Set the save file name of the log:

# 日志持久化保存
logging:
  file:
    name: C:\log\spring-log.log
  level:
    root: info

Run springBoot, and a log with a custom file name appears in the corresponding directory:
insert image description here
By default, the log has a maximum log limit, max-size. When the log file size exceeds this limit, springBoot will recreate a log and report an error.

lombok

SpringBoot's default log implementation is Lombok . Compared to getting the log object logger to print logs, lombok is a simpler way to print logs.

Use:
1. Add lombok framework support
2. Use @slf4j annotation to output logs.

Download the plugin EditStarters in idea:

insert image description here
Right-click in pom.xml, select Generate, and select the plugin you just downloaded
insert image description here
Search for lombok in the plugin to introduce dependencies:
insert image description here
use @Slf4j in the test class UserService to output the log:

package com.example.demo.model;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class UserService {
    
    

    @PostConstruct
    private void postConstruct(){
    
    
        //打印日志
        log.error("我是 UserService 的构造方法日志error!");
        log.warn("这是一个警告信息日志!");
   
    }
}

output:
insert image description here

Lombok principle explained

lombok is essentially a tool that can help us simplify some must-have Java code in the form of simple annotations.

For example, when we output the log, if we do not use lombok, we need to manually obtain the log object logger, and then call the method of this object. If you use lombok, you only need to add a @Slf4j annotation to get a log object, and then you can output the log.

What is the use of the @Slf4j annotation?
In fact, the function of this annotation is to automatically help us obtain the logger object, without requiring us to create it manually, which simplifies the code.
The Java source code we wrote needs to be converted into bytecode files for execution. In the idea directory, all the bytecode files are in the target directory. In the bytecode file, we look at the UserService class:
insert image description here
we add when writing the java source code Some annotations, and then lombok will further process, automatically generate some code according to the corresponding annotations, then compile the entire source code into bytecode files, and finally load and run on the JVM, as shown below:
insert image description here

lombok automatically generates code through annotations. The core is to parse annotations before generating code.

There are two ways to parse annotations:

  • Runtime parsing
    For annotations that can be parsed at runtime, @Retention must be set to RUNTIME, so that the annotation can be obtained through reflection. An interface AnnotatedElement is provided in the java.lang.reflect package. This interface defines several methods for obtaining annotation information, and classes, constructors, fields, methods, packages, etc. all implement this interface, and can naturally obtain annotations. information
  • Compile-time parsing
    Compile-time parsing is divided into two mechanisms:
    1. The Annotation Processing Tool toolkit
    apt was generated in JDK5, and JDK7 was marked as expired and deprecated. It was completely deleted in JDK8 and can now be
    replaced by the Pluggable Annotation Processing API, apt The toolkit was replaced for two reasons:
  • Not integrated into javac, need to run additionally
  • The api is concentrated under non-standard packages. 2. Pluggable Annotation
    Processing API
    Pluggable Annotation Processing API is also called JSR 269 , an alternative to apt above. It solves the defects of apt. When we execute it through javac, this api will be called. The execution process is as follows:
    insert image description here
    Lombok is essentially a "JSR API" program. In the process of use, the specific process is as follows:
  • 1.javac parses the source code and generates an abstract syntax tree AST
  • 2. Call the JSR 269 API at runtime
  • 3. lombok processes the syntax tree, finds the tree node corresponding to the annotation, and modifies it
  • 4.javac generates a bytecode file from the modified syntax tree and adds a new code block to the class file

Common annotations of lombok

  • @Getter : Annotated on a class or field, when the annotation is on the class, the getter method is generated for all fields, and when the annotation is on the field, only the getter method is generated for the field
  • @Setter : The method of use is the same as above, the difference is that the getter method is generated
  • @ToString : Annotate the class and add the toString method.
  • @EqualsAndHashCode : Annotate the class to generate hashCode and equals methods.
  • @NoArgsConstructor : Annotate the class to generate a parameterless constructor
  • @RequiredArgsConstructor : Annotate the class to generate constructors for fields that require special handling in the class
  • @AllArgsConstructor : Annotate the class to generate a constructor that includes all fields in the class
  • @Data : Annotate the class, generate setter and getter methods
  • @Slf4j : Annotate the class to generate log variables to output logs, which we have used above.

Advantages and disadvantages of lombok

advantage:

  • Automatically generate code through annotations, increasing development efficiency
  • The code becomes concise, and there is no need to pay too much attention to the corresponding method
  • Maintenance cost reduction

shortcoming:

  • Multi-argument constructors are not supported
  • Too concise, poor readability and completeness, increasing the difficulty of code reading

Article reference:
https://blog.csdn.net/ThinkWon/article/details/101392808

Guess you like

Origin blog.csdn.net/Merciful_Lion/article/details/124202159