[Spring Boot] (3) In-depth understanding of Spring Boot logs


foreword

In modern software development, the log is a vital tool. It records key information during the running of the application. When an error occurs in the running of the program, it can help developers quickly identify and solve existing problems . Reasonable logging can help us better understand the operation of the application, thereby improving the stability and maintainability of the application.

The main content of this article is to explore the use of logs in Spring Boot projects in depth. It mainly introduces the types of logs, definition of custom logs, log levels and persistence of output logs. In addition, it also includes using Lombok to output log information more simply and efficiently.

1. The role of log files

Log files play a vital role in software development and operation and maintenance. It records various events, statuses, and error messages generated during the operation of systems, applications, or services. The role of the log file is as follows :

  1. Troubleshooting and problem location : log files are an important tool for troubleshooting and locating problems. When an exception, error, or crash occurs in the system or application, the detailed information recorded in the log file can help developers or operation and maintenance personnel track the source of the problem, and help quickly locate and solve the problem.

  2. Performance analysis and optimization : By analyzing log files, you can understand the performance of the system or application. Identify bottlenecks, time-consuming operations, and resource consumption to optimize and improve system responsiveness and performance.

  3. Monitoring and early warning : Monitoring log files can monitor system operation status in real time. By setting specific log rules and alarm mechanisms, relevant personnel can be notified in time to deal with abnormalities or specific events in the system.

  4. Security audit and compliance : log files record the behavior and operation of the system and can be used for security audit and compliance check. This is important for meeting security standards and regulatory requirements, as well as protecting sensitive information.

  5. Data backup and restoration : log files record the historical state and operations of the system, which can be used for data backup and restoration, and restore to the state at a specific point in time.

  6. Tracing historical records : log files are important historical records during system operation, and are of great value for understanding system usage, user behavior, and interaction processes.

In general, log files are an important tool for system operation and maintenance. They can provide rich information and data to help developers, operation and maintenance personnel and administrators monitor and maintain the healthy operation of the system, find and solve problems in time, and optimize system performance. , and meet security and compliance requirements. Therefore, good logging and management is an essential part of a quality software and system.

2. Logs in Spring Boot

Spring Boot provides a powerful log function, which can easily view the output log information and flexibly configure the log format.

2.1 View the output log information

Spring Boot uses Logback as the logging framework by default, which can output logs to the console (Console) and log files. During the development and debugging process, we can directly view the log information output on the console.

For example, the log information output when starting the Spring Boot project:


The above log information includes timestamp, log level, process ID, thread information, class name and log content, etc. Different log levels correspond to different colors, such INFOas green, WARNyellow, ERRORand red, which is convenient for distinguishing the severity of logs.

2.2 Log format

2. Logs in Spring Boot

Spring Boot provides a powerful log function, which can easily view the output log information and flexibly configure the log format. The following will introduce how to view the output log information and log format configuration.

2.1 View the output log information

Spring Boot uses Logback as the logging framework by default, which can output logs to the console (Console) and log files. During the development and debugging process, we can directly view the log information output on the console.

For example, we can see log information similar to the following in the console output of the Spring Boot application:

2023-08-06 15:30:00.123  INFO 12345 --- [main] com.example.Application : Starting Application on localhost with PID 12345 (D:\workspace\project\target\classes started by user in D:\workspace\project)
2023-08-06 15:30:00.456  INFO 12345 --- [main] com.example.Application : Started Application in 2.345 seconds (JVM running for 3.456)

The above log information includes timestamp, log level, process ID, thread information, class name and log content, etc. Different log levels correspond to different colors, such INFOas green, WARNyellow, ERRORand red, which is convenient for distinguishing the severity of logs.

2.2 Log format

Spring Boot allows us to flexibly configure the output format of the log. Log format configuration is usually achieved by adding the corresponding configuration in application.ymlor .application.properties

For example, we can application.ymladd the following configuration in :

logging:
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} : %msg%n"
    file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} : %msg%n"

The above configurations set the log format for console output and log file output respectively. %dRepresents the timestamp, %threadrepresents the thread information, %-5levelrepresents the log level (left-aligned, 5 characters wide), %logger{36}represents the class name (only the last 36 characters of the class name are displayed to prevent the class name from being too long), %msgrepresents the log content, and %nrepresents a newline.

By configuring different log formats, we can customize the output content and style of the log to meet different needs.

It should be noted that the log configuration is not limited to the above two output formats, Spring Boot also supports more log configuration options, such as log file path, log rolling strategy, log level, etc. According to actual needs, you can add corresponding log configurations in application.ymlor to meet different log output and management requirements.application.properties

3. Custom log output

In Spring Boot, we can customize log output, including selecting different log frameworks, getting log objects and using log objects to print logs. These three aspects are introduced below.

3.1 Log framework

Logging Facades and Logging Implementations are two commonly used logging-related components in Java applications .

  • The log facade is an interface or abstraction layer that provides a unified log interface, allowing applications to record logs in a unified way without depending on specific log implementations.
  • The log implementation is a specific log framework, which implements the interface defined by the log facade, and is responsible for outputting log information to the corresponding destination, such as the console or log file.

In the Java ecosystem, there are several logging facades and logging implementations to choose from. Among them, the common log facades are commons-loggingand SLF4J, and the common log implementations are log4j 1/2and .JUL(Java Util Logging)logback

  1. Commons-Logging: It is the Apache Commons Logging component, which is a simple encapsulation of the JDK log. It provides a unified interface for developers to record logs, and can transparently switch between different log implementations, but it is not common in actual use because its functions are relatively limited and its development is relatively early.

  2. SLF4J(Simple Logging Facade for Java): It is a log facade that is widely used at present . It provides a set of simple abstract interfaces that enable developers to record logs in a unified manner. Unlike Commons-Logging, SLF4J it is more elegantly designed and full-featured, and it has become the logging facade of choice for many Java applications .

After selecting the log facade, we need to select the corresponding log implementation to actually output log information. Common log implementations are:

  1. Log4j 1: Apache Log4j 1.x version, an earlier log implementation with powerful functions and flexible configuration. However, due to the older version, some features may appear outdated in modern applications.

  2. Log4j 2: Apache Log4j 2.x version, an Log4j 1upgraded version of , with more functions and performance optimization. Log4j 2Both are supported SLF4Jso it can be seamlessly SLF4Jintegrated with .

  3. JUL(Java Util Logging): It is the log implementation that comes with the JDK. It is relatively simple and does not require additional dependencies, but its functions are relatively limited. Some Java libraries and frameworks use JUL as the default logging implementation since no additional libraries are required.

  4. Logback: is Log4j 1a logging implementation designed by the original author of , as a replacement for Log4j. LogbackIt is a high-performance and powerful logging framework, which is SLF4Jhighly integrated with , so SLF4Jit works very well when used together.

When choosing a logging framework, it is recommended to use it SLF4Jas a logging facade, combined with corresponding logging implementations, such as Logbackor Log4j 2. In this way, the flexibility of log output can be maintained, and it can be switched to other log implementations without changing the application code, while taking into account performance and function requirements.

3.2 Acquisition of log objects

In the Spring Boot component class, we can use LoggerFactorythe static method of the class getLogger(Class)to get the log object. Usually, we will use the log object as a member variable of the class so that it can be used in each method of the class.

@RestController
public class LoggerController {
    
    
    private Logger logger = LoggerFactory.getLogger(LoggerController.class);
    
    @RequestMapping("/log")
    public void logging(){
    
    
        logger.trace("i am trace");
        logger.debug("i am debug");
        logger.info("i am info");
        logger.warn("i am warn");
        logger.error("i am error");
    }
}

3.3 Use the log object to print logs

Run the startup class, and then enter in the browser to localhost:8080/logtrigger the printing of log information:


At this point, you can see the log information printed out on the console, but we found that only three logs INFO, WARN, and were printed, but and were not printed. The reason is related to the level of the log.ERRORTRACEDEBUG

4. Log level

The log level refers to the importance or severity of the log information, and different levels of log information correspond to different events and states . In Spring Boot, the log level is used to control the detail level of the log output. You can control which log information will be recorded and output by setting different log levels, so as to flexibly control the amount and content of the log .

Since the default log level output by Spring Boot is INFO, you can only see INFOand higher basic log information.

4.1 The role of log levels

  • The function of the log level is to help developers filter and locate log information in different scenarios . By setting an appropriate log level, more detailed log information can be recorded during the development phase to help debug and troubleshoot problems;

  • In a production environment, you can set a lower log level to record only important information, so as to avoid excessive log output from affecting system performance .

4.2 Classification of log levels

Common log levels (low to high) include:

  1. TRACE(Lowest level) : The most detailed log information, used to track the running process of the program, usually used in the development and debugging stages.

  2. DEBUG: Debug-level log information, used to output debugging-related information, which is convenient for troubleshooting.

  3. INFO: General information level, used to output general information about the running status of the program.

  4. WARN: Warning level, used to record situations that may cause problems, but do not affect the normal operation of the program.

  5. ERROR: Error level, used to record error information, indicating that an error has occurred in the program.

  6. FATAL(highest level) : The most severe error level, used to log fatal errors, indicating that the program cannot continue to run.


Log levels can be divided into two categories in descending order:

  1. Debug level : including TRACEand DEBUG, used to output detailed information during the running of the program, usually in 开发和调试阶段use.

  2. Runlevels : including INFO, WARN, ERRORand FATAL, are used to output program running status and potential problems, which can be 生产环境used in .

4.3 Set the log level through the configuration file

In Spring Boot, the log level can be set through the configuration file. By default, Spring Boot uses configuration in application.ymlor to control the logging level.application.properties

Here's application.ymlan example of setting the log level in :

logging:
  level:
    root: INFO  # 根日志级别为 INFO,即默认情况下的日志级别
    com:
      example:
        controller: DEBUG  # com.example.controller 包及其子包的日志级别为 DEBUG
        component: ERROR  # com.example.component 包及其子包的日志级别为 ERROR

In the above example, we set log levels for three different packages: the root log level is INFO, com.example.controllerthe log level for the package and its subpackages is DEBUG, and com.example.componentthe log level for the package and its subpackages is ERROR.

By setting different log levels, you can flexibly control the detail level of log output in different scenarios, helping developers to better debug and monitor applications.

5. Log Persistence

5. Log Persistence

During the running of the application, the generated log information usually needs to be persisted for the purpose of subsequent log audit, troubleshooting and performance analysis. Log persistence is the process of saving log information to persistent storage media, such as log files, databases, or remote log servers. In Spring Boot, common log persistence methods include:

5.1 Log output to file

By default, Spring Boot will output logs to the console (Console), but usually in order to better manage and maintain logs, we want to output logs to files. Logging can be output to a file by adding the corresponding configuration in application.ymlor .application.properties

For example, application.ymladd the following configuration in :

logging:
  file:
    name: myapp.log  # 设置日志文件的名称,可以是任意文件名

The above configuration will append the log output to myapp.logthe file named . Log files are saved in the application's working directory, usually the root of the project .

5.2 Log output to database

Sometimes, we want to store log information in a database for easier query and analysis. Spring Boot can implement the function of outputting logs to the database through the log framework.

First, we need to create a database table to hold the log information. The database table structure can be designed according to actual needs, for example, including log level, timestamp, log content, class name, method name and other fields.

Then, we can use the appropriate logging framework to configure the output of log information to the database. For Logback, you can use it DBAppenderto output logs to the database.

6. Use Lombok to achieve simpler log output

Lombok is a Java library that simplifies the Java development process by automatically generating some common code for Java classes through annotations. In terms of log output, Lombok can help us use log objects more conveniently, avoiding the tedious process of manually defining log variables.

6.1 Add Lombok dependencies through the EditStarts plugin

First, we need to add Lombok dependency in the project's build file (such as pom.xml) in order to use Lombok in the project. EditStartsIf the Lombok dependency is not checked when the Spring Boot project is created, you can add the Lombok dependency through the plug-in in IDEA :

  1. install EditStartsplugin


2. Right-click in the pom.xml file and select it Generate.


3. Select Edit Starters, if not, the installation is not successful.


4. After clicking, the following interface appears, click OK.


5. Then the following interface appears, Searchsearch for the required dependencies in and add them.

6.2 Output log

Using Lombok to simplify logging output is very simple. @Slf4jWe only need to add annotations to the class , and Lombok will automatically generate a loglog object named for us.

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

@RestController
@Slf4j
public class LoggerController {
    
    

    @RequestMapping("/log")
    public void logging(){
    
    
        log.trace("i am trace");
        log.debug("i am debug");
        log.info("i am info");
        log.warn("i am warn");
        log.error("i am error");
    }
}

In the above example, we use @Slf4jthe annotation on the class, Lombok will LoggerController generate a loglog object named for the class. Afterwards, we can directly use logthe object to output different levels of log information without manually defining the log object.

Through the simplification of Lombok, we can achieve log output more conveniently, avoid the trouble of manually defining log objects and importing log framework packages, and improve the readability and simplicity of the code.

Guess you like

Origin blog.csdn.net/qq_61635026/article/details/132124489