1. Logging framework

The origin of the log:

(1) Output key data to the console in the process of system development;

(2) Too many console output statements in the system are not easy to maintain, so integrate the console output statements into the log JAR package xxxlogging.jar.

(3) A new log JAR package is generated when the log JAR package is upgraded. Xxxlogging-update. jar is replaced by the log JAR package already used in the system.

(4) Create log facade (log abstraction layer) logging-abstract. Jar by referring to the relationship between JDBC and database driver (JDBC only calls interface, each major database vendor provides implementation class).

⑤ The use of log in the project only need to import specific log implementation, log framework has implemented the log abstraction layer;

Common logging frameworks on the market:

JUL, JCL, jboss-Logging, logback, log4j, log4j2, slf4J……

Introduction to the Framework:

Logging Framework name Belongs to type Introduction to the
JCL(Jakarta Commons Logging) Logging facade A common logging API provided by Apache
SLF4j(Simple Logging Facade for Java) Logging facade SLF4J provides a unified logging interface
jboss-logging Logging facade Jboss-logging is a logging framework similar to SLF4J
Log4j(Log for java) The logging implementation Apache foundation is an excellent open source logging framework
JUL(java.util.logging) The logging implementation Log output provided in the JDK
Log4j2 The logging implementation Apache Foundation’s updated version of Log4J supports plug-in architecture
Logback The logging implementation Logback is another open source logging framework designed by the founders of Log4J
  • In the use of logging framework, choose a log facade as the call interface, choose a log framework implementation as the concrete implementation;
  • The JCL FrameWork is used by default in Spring Boot.
  • In Spring Boot, the log facade integrated by Starter is SLF4j, and the log implementation is logback.

For details about the above frameworks, see Comparison of Common Logging Frameworks

2. SLF4J framework

SLF4J (Simple Logging Facade for Java) is a Simple Logging Facade. It is not a specific Logging solution and only serves a variety of Logging systems. Officially, SLF4J is a simple Facade for logging systems that allows end users to use the logging systems they want when deploying their applications.

SLF4J is a logging abstraction layer that allows you to use any logging system and switch to other logging frameworks at any time without having to modify already written programs. SLF4J is only responsible for developing logging standards, not for implementing logging systems. SLF4J is only responsible for two things:

(1) Provides a log interface.

② Provide methods to obtain specific log objects;

2.1 Use of SLF4j framework

When we invoke logging methods using logs, we should invoke logging abstraction layer methods, not logging concrete implementation classes.

SLF4J framework uses the following steps:

① Import SLF4J JAR package and logback implementation JAR package;

② Use the method provided by SLF4J to use logging;

Official code examples:

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

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World"); }}Copy the code
  • We can’t log just by importing the slf4J-api.jar package. SLF4J only provides log operation interface, does not provide specific operation methods, if you want to use SLF4J as the log operation of the facade also need to import specific log implementation framework;

    Jar Logback -classic.jar Logback -core. Jar package slf4J-api. jar Logback -classic.jar Logback -core. SLF4J framework is used as the facade of logging operations, and Logback framework is used as the concrete implementation class of logging operations.

  • If you use a logging implementation class that does not directly implement the SLF4J framework, you need to introduce an intermediate mediation package for integration calls;

    For example, to perform log operations using the SLF4J and Log4j frameworks, you need to rely on slf4-api.jar log4j.jar and slf4j-log412.jar adaptation package.

The JAR package relationships that the SLF4J framework needs to rely on when integrating with other logging frameworks are shown below:

Each logging implementation framework has its own configuration file, and with SLF4J, the configuration file is written to the logging implementation framework itself.

The official documentation for SLF4J is the SLF4J User Manual

2.2 SLF4j framework unified log output

When we carry out framework integration, we will encounter the problem that the log output framework used by different frameworks is not unified, so we need to unify the log framework.

For example, our system development plan uses SLF4J and logback logging framework for logging output, and our project uses SSH framework. However, Spring Framework’s default log output is commons-logging Framework and Hibernate Framework’s default log output is Jboss-logging Framework. Therefore, we need to unify the log output of SLF4j Framework and shield other log output frameworks in the system.

How to unify all logs in the system to SLF4J:

(1) Exclude other logging frameworks in the system;

(2) Replace the original logging framework with a tundish;

③ We import other implementations of SLf4J;

For example, if slF4J is used as the facade framework for logging and Logback is used as the implementation framework for logging in the project, slF4J and LOGback-related JAR packages need to be imported. However, the logging framework used by the integrated Spring Frame framework in the project is JCL. In this case, the JCL logging framework needs to be removed from the project and introduced into the middle

The jCL-over-slfj4.jar package replaces the original JCL JAR package. In this way, the log output in the project is unified to slF4J as the facade framework of the log, logback as the implementation framework of the log.

Unified logging Framework using SLF4J:

Related links: SLF4J solves legacy issues

3. Spring Boot and Logs

3.1 Log Configuration in Spring Boot

The spring-boot-starter-web dependency is imported in pm. XML.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

The spring-boot-starter-web dependency includes the spring-boot-stater dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.3.4. RELEASE</version>
    <scope>compile</scope>
</dependency>
Copy the code

The spring-boot-stater dependency includes the spring-boot-starter-logging dependency for configuring log correlation.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <version>2.3.4. RELEASE</version>
    <scope>compile</scope>
</dependency>
Copy the code

Composition of spring-boot-starter-logging dependencies

Spring Boot uses SLF4J + Logback as the log output, and replaces the default log framework in other integrated frameworks to realize the unification of the log output framework.

3.2 Spring Boot Resolve log framework Conflicts

Pom. XML writes the parent class dependency pointing to spring-boot-starter-parent-xxx.pom to configure the Spring Boot framework.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4. RELEASE</version>
    <relativePath/> <! -- lookup parent from repository -->
</parent>
Copy the code

Spring-boot-starter-parent-xxx. Pom specifies the spring boot dependencies for all frameworks. Spring-boot-dependencies.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4. RELEASE</version>
</parent>
Copy the code

Spring-boot-dependencies. Pom specifies the version of the JAR package and excludes the default logging framework in the framework;

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-console</artifactId>
    <version>${activemq.version}</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
Copy the code

You can also exclude the default logging framework when importing the framework. For example, exclude the default logging framework configuration in Spring Boot.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-logging</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>
Copy the code

When Spring Boot excludes default logging frameworks in other frameworks, use the < Exclusion >
tag in the POP.xml file to exclude dependent frameworks.

Spring Boot log configuration summary:

① At the bottom of Spring Boot, slF4J + Logback is used for logging;

Spring Boot replaces other logging frameworks with SLF4J frameworks.

(3) The log intermediate replacement package actually calls slf4J methods;

(4) When we introduce other frameworks, we need to remove the default logging framework from the framework;

In a word: Spring Boot automatically ADAPTS all logging, and slF4J and LogBack frameworks are used as the underlying logging framework. When we introduce other frameworks, we need to remove the default logging framework from the framework.

4. Use logs

4.1 Default Log Configuration

Spring Boot has configured logging for us by default and can be used directly.

  • Log output levels are as follows: Trace < DEBUG < info < WARN < error;

  • The log output level can be adjusted. After log output is configured, logs take effect only at the current and subsequent levels.

    For example, if the output of info logs is set, trace and DEBUG logs will not be output.

  • The default Spring Boot log output level is info (root).

Code examples:

@RunWith(SpringRunner.class)
@SpringBootTest
class Springboot03LoggingApplicationTests {

	Logger logger = LoggerFactory.getLogger(getClass());

	/** * Log output level: trace
	@Test
	void contextLoads(a) {
		logger.trace("Trace Level logs...");
		logger.debug(Debug level logs...);
		// The default Spring Boot log level is info. If no log level is specified, the default Spring Boot log level is root.
		logger.info(Info level logs...);
		logger.warn("Warn level logs...");
		logger.error("Error level logs...); }}Copy the code

Output after run:

. ____ _ __ _ _ / \ \ / ___ '_ __ _ _) (_ _ __ __ _ \ \ \ \ (\ ___ () |' _ | '_ | |' _ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.4. RELEASE) the 2020-10-20 14:46:25. 17748-049 the INFO [main] B.S.S pringboot03LoggingApplicationTests: Starting Springboot03LoggingApplicationTests on YOGA-S740 with PID 17748 (started by Bruce in E:\workspace\workspace_idea03\ demo-springboot \springboot03_logging) 2020-10-20 14:46:25.051 INFO 17748 -- [main] .b.s.Springboot03LoggingApplicationTests : No active profile set, falling back to default profiles: Default 14:46:26 2020-10-20. 17748-248 the INFO [main] O.S.S.C oncurrent. ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor' 2020-10-20 14:46:26.520 INFO 17748 -- [main] .b.s.Springboot03LoggingApplicationTests : Started Springboot03LoggingApplicationTests in 1.745 seconds (JVM running 2.833) for the 2020-10-20 14:46:26. 716 INFO 17748 - [the main] B.S.S pringboot03LoggingApplicationTests: info log... The 2020-10-20 14:46:26. 716 WARN 17748 - [the main] B.S.S pringboot03LoggingApplicationTests: WARN level log... The 2020-10-20 14:46:26. 716 ERROR 17748 - [the main] B.S.S pringboot03LoggingApplicationTests: ERROR level log...Copy the code

You can modify the default logging configuration of Spring Boot using the application.properties file, which can also modify other Spring Boot configurations. For details, see Spring Boot Configuration.

① Logging. level: Specifies the log output level. You can configure the log output level separately for each package and class in the project.

② Logging.file. path: specifies the log output path.

③ Logging.file. name: Specifies the log output name and path. If path and name are configured at the same time, the path configuration does not take effect.

④ Logging.pattern. Console: specifies the style of the console output.

logging.file.pathlogging.file.fileOutput differences:

logging.file.name logging.file.path Example Description
(none) (none) Only log information is output on the console
Specify file name (none) my.log Specifies the name of the output log file. The name can be an exact location or relative to the current project directory.
(none) The specified directory /var/log The outputspring.logLog files to the specified directory, the name can be an exact location or relative to the current project directory.

Log style output configuration items:

Configuration items Configure the content
%d Indicates the date and time configuration
%thread Represents the thread name
%-5level Represents 5 character widths displayed from the left
%logger{50} Indicates that the logger name can contain a maximum of 50 characters. Otherwise, the logger name is divided by periods.
%msg Represents log messages
%n newline

Example log output style: % D {YYYY-MM-DD HH: MM :ss.SSS} [%thread] %-5level % Logger {50} -% MSG %n

Code examples:

You can configure the log output level individually for each package and class
logging.level.cn.bruce=trace
# path Specifies the output directory of logs. A spring folder will be created in the root directory of the disk, and a spring.log file will be generated in the directory to record log information
# create a folder in the project directory without /, and generate the log output file spring.log in the folder
#logging.file.path=/spring
# name Specifies the name and path of the output file. The file location is optional. If path and name are written at the same time, only name takes effect
logging.file.name=E:/spring/demo-spring.log
# specify the log style for the console output
# %d indicates the date and time,
# %thread indicates the name of the thread,
# %‐ 5Level: level displayed 5 character widths from the left
# %logger{50} Indicates that the maximum length of logger name is 50 characters, otherwise split by period.
# % MSG: log message,
# %n is a newline character

logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} --> [%thread] --> %-5level --> %logger{50} --> %msg%n
# specify the file output logging style
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} === %msg%n
Copy the code

4.2 Specifying log Configuration

We can specify configuration files for the logging framework as long as they are placed under the classpath. SpringBoot will not use the default configuration.

Configuration files corresponding to different logging frameworks:

Logging System Customization
Logback logback-spring.xml.logback-spring.groovy.logback.xml, or logback.groovy
Log4j2 log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging) logging.properties
  • logback.xml: Configuration files are directly recognized by the logging framework;
  • logback-spring.xml: The log framework does not load configuration items of logs directly. The Spring Boot parses logs. You can use the advanced Profile function of Spring Boot. Refer to Spring Boot configuration above for more information.

Note: An error occurs if you use logback. XML and still use Spring Boot’s advanced Profile feature.

Log configuration described in the Spring Boot official documentation: Log configuration for Spring Boot

5. Switch the log framework

Spring Boot allows us to replace the default SLF4J + LogBack logging framework architecture with another logging configuration framework. For example, we switched the logging framework to slF4J +log4j.

Modify the POM.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <! Select logback from SpringBoot framework
        <exclusion>
            <artifactId>logback-classic</artifactId>
            <groupId>ch.qos.logback</groupId>
        </exclusion>
        <! Select logback from SpringBoot framework
        <exclusion>
            <artifactId>log4j-to-slf4j</artifactId>
            <groupId>org.apache.logging.log4j</groupId>
        </exclusion>
    </exclusions>
</dependency>

<! Log4j adaptor = logback;
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
</dependency>
Copy the code

It is not recommended to switch to log4J framework in actual development. Logback or Log4j2 are recommended because of performance problems of log4J framework.

Switch tolog4j2As a logging output framework

Modify the POM.xml file

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <! Starter -->
        <exclusion>
            <artifactId>spring-boot-starter-logging</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<! Log4j starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Copy the code

Dependencies after switching to the log4j2 framework