[springboot] Architecture of the Slf4j logging framework

Students who have just come into contact with the java log log may be frightened by various log frameworks, including the jars between the various log frameworks always conflicting, and many other small partners have a headache. Then the content of this article is to introduce the development process of various java log frameworks, the relationship between them, and how to select them.

1. Various logging toolkits

1.1. Logging Framework

  • JDK java.util.logging package: java.util.logging is a java log package released by jdk1.4, which can be said to be a log toolkit with a long-term application
  • log4j: An open source project of apache, which provides strong java log support, and even provides interfaces to other languages ​​including C, C++, .Net, and PL/SQL, so as to realize multi-language coexistence of distributed environment log printing. Updates have been discontinued, so it is not recommended.
  • Logback: Another open source log component designed by the founder of log4j, as the default log framework of Spring Boot, it is widely used.
  • log4j2: Apache Log4j2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j1.x, and provides many of the improvements available in Logback while fixing some issues in the Logback architecture. It is based on the development of Disruptor (an open source lock-free concurrency framework) based on LMAX Company, which improves the defects of Log4j and Logback in terms of architectural design, has ultra-high throughput and low latency, and has better performance than Log4j1.x and Logback.

1.2. Log facade

  • commons-logging: A member of the Apache commons class library, as a log facade, it can automatically choose whether to use log4j or JDK logging, but it does not depend on the API of Log4j and JDK Logging. If the classpath of the project contains the log4j class library, log4j will be used, otherwise JDK Logging will be used.
  • SLF4J: It can be said to be the most widely used log facade. It provides a log abstraction layer that allows you to use any log library in the background. Such as: log4j, log4j2, logback

1.3 The significance of the existence of the log facade

insert image description here

Why not just use the logging framework, but come up with a logging facade?
The log facade (SLF4J) is mainly to provide a standard and standardized API framework for Java log access. Its main significance is to provide an interface. The specific implementation can be implemented by other log frameworks, such as log4j and logback. For general Java projects, the logging framework will choose slf4j-api as the facade, coupled with a specific implementation framework (log4j, log4j2, logback, etc.), and use a bridge in the middle to complete the bridging.

For the several logging frameworks introduced above, each logging framework has its own separate API. To use the corresponding framework, the corresponding API must be used, which greatly increases the coupling requirements of the application code for the logging framework. With the SLF4J facade, programmers will always program for SLF4J, which can easily and quickly replace the underlying logging framework without causing corresponding modifications to the business code.

When logging with SLF4J, it is usually necessary to define a Logger variable in each class that needs to log, as follows:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
public class LogTestController {
    
    
    private static final Logger logger = LoggerFactory.getLogger(LogTestController.class);

    @GetMapping("/test")
    public void test(){
    
    
        logger.trace("Trace 日志...");
        logger.debug("Debug 日志...");
        logger.info("Info 日志...");
        logger.warn("Warn 日志...");
        logger.error("Error 日志...");
    }
}

This is obviously repetitive work and reduces development efficiency. If you introduce Lombok into your project, you can use the @Slf4j annotation provided by it to automatically generate the above variable. The default variable name is log. If we want to use the idiomatic LOGGER is used as the variable name, then you can add the lombok.config file in the root directory of the project, and add lombok.log.fieldName=LOGGERthe configuration items in the file.

2. Log frame selection

  • Spring Boot's default logging framework uses Logback
  • Among them, Log4j can be considered as an outdated function library, which has stopped updating and is not recommended for use. In contrast, its performance and functions are also the worst.
  • Although logback is the default of Spring Boot, its performance is still inferior to Log4j2. Therefore, at this stage, Log4j2 is the first choice for logging (the log4j series has experienced security disturbances, please use the new version after the bug has been fixed).

SLF4J + Log4j2 is our recommended logging option.

Performance test results
insert image description here

Reference: log4j2 official website

3. Log level

Before detailing the integration configuration of each log framework, let's first have a general understanding of the most common log levels: ERROR, WARN, INFO, DEBUG and TRACE. Like others, such as ALL, OFF and FATAL should basically not be involved in the development process. Therefore, the following common log levels are introduced from low to high.

  1. TRACE: Tracking. Generally, it is useful to debug the performance of the core system or track problems. This level is very low. Generally, it is not enabled. After it is enabled, the log will fill up the disk very quickly.
  2. DEBUG: Debug. Everyone should be familiar with this. The development process is mainly to print and record some running information and the like.
  3. INFO: Information. This is the most common, and most of them default to this level of logs. Generally, some interaction information, some request parameters, and so on are recorded. It is convenient to locate the problem, or use it when restoring the on-site environment. This log is relatively important.
  4. WARN: Warning. This generally records potentially error-prone information. For example, when starting, a certain configuration file does not exist or a certain parameter is not set.
  5. ERROR: Error. This is also relatively common. Generally, it is output when an exception is caught. Although an error occurs, it does not affect the normal operation of the system. But it may lead to system errors or downtime.

The log level from small to large is trace<debug<info<warn<error<fatal. Since the default log level of the log framework is usually set to INFO, the trace and debug logs in the sample trace and debug levels in section 1.3. cannot be seen.

2020-08-17 13:59:16.566  INFO c.z.b.l.controller.LogTestController     : Info 日志...
2020-08-17 13:59:16.566  WARN  c.z.b.l.controller.LogTestController     : Warn 日志...
rn 日志...
2020-08-17 13:59:16.566 ERROR  c.z.b.l.controller.LogTestController     : Error 日志...

Four, common terminology concept analysis

  1. appender: mainly controls where the log is output, such as: file, database, console printing, etc.
  2. logger: used to set the log printing level of a package or a specific class, and specify the appender
  3. root: is also a logger, a special parent logger. All child loggers will eventually stream output to root unless additivity="false" is configured in the child logger.
  4. rollingPolicy: It is not good to store all logs in one file, so you can specify a rolling policy to store log files according to a certain period or file size.
  5. RolloverStrategy: Log cleanup strategy. Usually refers to how long the log is retained.
  6. Asynchronous log: Open a separate thread to write the log to achieve the purpose of not blocking the main thread.

insert image description here

  • To synchronize the log, the main thread cannot continue to execute until the log is written to the disk.
  • Asynchronous log, the main thread writes the log just puts the log message into a queue, and then continues to execute downward. This process is completed at the memory level. Afterwards, a dedicated thread obtains log data from the queue and writes it to disk, so the main thread is not blocked. The main thread (core business code) executes efficiently.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/122893005