Three, the log of the SpringBoot framework

3. the log of the SpringBoot framework

1. Log Framework

Origin of the log:

Output key data to the console during system development;

Too many console output statements in the system are not easy to maintain, and the console output statements are integrated into a log jar package


Upgrade the log jar package to generate a new log jar package,

Facing the problem of replacing the log jar package that has been used in the system;

Refer to the relationship between JDBC and database drivers (JDBC is just a calling interface, and major database vendors provide implementation classes) to create a log facade (log abstraction layer)


To use logs in the project, you only need to import specific log implementations, and the log framework implements the log abstraction layer;

Common log frameworks on the market:

JUL, JCL, Jboss-logging, logback, log4j, log4j2, slf4j...

Introduction to the framework:

Log frame nameBelonging toIntroduction
JCL (Jakarta Commons Logging)Log facadeA general logging API provided by Apache
SLF4j(Simple Logging Facade for Java)Log facadeSLF4J provides a unified logging interface
jboss-loggingLog facadejboss-logging is a logging framework similar to slf4j
Log4j(Log for java)Log implementationAn excellent open source logging framework from the Apache Foundation
JUL(java.util.logging)Log implementationLog output provided in JDK
Log4j2Log implementationThe upgraded version of Log4J launched by the Apache Foundation, which supports plug-in structure
LogbackLog implementationLogback is another open source logging framework designed by the founder of log4j
  • When using the logging framework, choose a logging facade as the calling interface, and choose a logging framework implementation as the specific implementation;
  • The JCL framework used by Spring Boot's underlying Spring FrameWork framework by default;
  • The log facade integrated by Starter in Spring Boot is SLF4j, and logback is selected for log implementation;

For a detailed introduction to the above frameworks, please refer to: Comparison of Common Log Frameworks

2. SLF4J framework

SLF4J (Simple Logging Facade for Java) is a simple log facade, not a specific log solution, it only serves a variety of log systems. According to the official statement, SLF4J is a simple facade for the logging system, allowing end users to use the logging system they want when deploying their applications.

SLF4J is a log abstraction layer that allows you to use any log system, and you can switch to other log frameworks at any time without modifying the already written program. SLF4J is only responsible for the development of logging standards, not the specific implementation of the logging system. SLF4J is only responsible for two things:

Provide log interface;

Provide methods to obtain specific log objects;

2.1 The use of SLF4j framework

When we use the log to call the method in the log, we should call the method of the log abstraction layer, not the specific implementation class of the log.

Steps to use SLF4J framework:

Import the jar package of SLF4J and the realization jar package of logback;

Use the method provided by SLF4J to use the log;

Official code example:

import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main (String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); "Hello World" ); } } Copy code
  • We only import

    The package cannot implement log operations. SLF4J only provides a log operation interface, and does not provide a specific operation method. If you want to use SLF4J as the facade of the log operation, you need to import a specific log implementation framework;

    For example: use SLF4J framework and Logback framework to complete the log operation together, you need to import

    Package, that is: use the SLF4J framework as the facade of the log operation, and the Logback framework as the specific implementation class of the log operation;

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

    For example: use SLF4J framework and log4j framework to complete log operations, except for dependencies

    The package also needs to rely on the adaptation package

The relationship between the jar packages that the SLF4J framework needs to rely on when integrating with other logging frameworks is shown in the following figure:

Each log implementation framework has its own configuration file. After using SLF4J, the configuration file is still written as the configuration file of the log implementation framework itself.

The official document of SLF4J : SLF4J User Manual

2.2 SLF4j framework unified log output

When we are implementing framework integration, we will encounter the problem that the log output frameworks used by different frameworks are not unified, and we need to unify the log framework.

For example: Our system development plan uses slf4j and logback log framework for log output, and our project uses SSH framework. However, the default log output of the Spring Framework framework is the commons-logging framework, and the default log output of the Hibernate framework is the jboss-logging framework. At this time, we need to uniformly output the logs of the SLF4j framework to shield other log output frameworks in the system.

How to unify all logs in the system to slf4j:

Exclude other log frames in the system first;

Replace the original log frame with an intermediate package;

We import other implementations of slf4j;

For example: Use slf4j as the log facade framework in the project, and logback as the log implementation framework. You need to import the jar packages related to slf4j and logback. However, the logging framework used by the integrated Spring Frame framework in the project is JCL. At this time, the JCL logging framework needs to be excluded from the project and introduced in the middle


Replace the original JCL jar package. In this way, the log output in the project is unified to slf4j as the log facade framework, and logback as the log implementation framework.

Use slf4j unified log framework icon:

Related links: slf4j solves the remaining problems

3. Spring Boot and log

3.1 Configuration of log in Spring Boot


< Dependency > < the groupId > org.springframework.boot </the groupId > < the artifactId > Spring-Boot-Starter-Web </the artifactId > </dependency > copy the code

Included in dependency

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

Included in dependency
Dependency is used to configure log related;

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

Dependent composition

Spring Boot bottom use

slf4j + logback
As the log output, it replaces the default log framework in other integrated frameworks to realize the unification of the log output framework.

3.2 Spring Boot solves the conflict of logging framework

The dependency point of the parent class is written in
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 Repository from parent -> </parent > copy the code

Specify the dependency packages that reference all frameworks in Spring Boot

< Parent > < the groupId > org.springframework.boot </the groupId > < the artifactId > Spring-Boot-Dependencies </the artifactId > < Version > 2.3.4.RELEASE </Version > </parent > copy the code

Specify the version of the jar package in and exclude the default log frame 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 code

When Spring Boot excludes the default logging framework in other frameworks,

Used in the file
The label performs the exclusion of the dependent framework.

Summary of log configuration in Spring Boot:

Spring Boot bottom layer adoption

slf4j + logback
Way of logging;

Spring Boot replaced other logging frameworks with


The replacement package in the middle of the log is actually called


When we introduce other frameworks, we need to remove the default log framework in the framework;

One sentence summary: Spring Boot can automatically adapt to all logs, and the bottom layer uses

The framework serves as a log record. When we introduce other frameworks, we need to remove the default logging framework in the framework.

4. Use of logs

4.1 Default log configuration

Spring Boot configures the log for us by default and can be used directly.

  • The log output levels, from high to low, are as follows:

    trace<debug <info <warn <error

  • The output level of the log can be adjusted. After the log output is set, the log will only take effect at the current set level and later levels.

    For example: set

    Level of log output, then
    Level and
    The log of the level will not be output;

  • The default log output level of Spring Boot is


Code example:

@RunWith(SpringRunner.class) @SpringBootTest class Springboot03LoggingApplicationTests { Logger logger = LoggerFactory.getLogger(getClass()); /** * Log output level: from high to low trace<debug<info<warn<error * The output level of the log can be adjusted; after setting the log output level, the log will only take effect at the current level and later levels */ @Test void contextLoads () { logger.trace( "trace level log..." ); logger.debug( "debug level log..." ); //Spring Boot outputs info level log by default. If no log level is specified, Spring Boot default level (root level) is used "info level log ..." ); logger.warn( "Warn level log..." ); logger.error( "error level log..." ); } } Copy code

Output content after running:

. ____ _ __ _ _ /\/___'_ __ _ _(_)_ __ __ _///\ (()\___ |'_ |'_| |'_//_` |///\ \\/___)| |_)| | | | | || (_| |)))) '|____| .__|_| |_|_| |_\__, |//// ==========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.4.RELEASE) 2020-10-20 14:46:25.049 INFO 17748 --- [main] .bsSpringboot03LoggingApplicationTests: 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] .bsSpringboot03LoggingApplicationTests: No active profile set, falling back to default profiles: default 2020-10-20 14:46:26.248 INFO 17748 --- [main] ossconcurrent.ThreadPoolTaskExecutor: Initializing ExecutorService'applicationTaskExecutor' 2020-10-20 14:46:26.520 INFO 17748 --- [main] .bsSpringboot03LoggingApplicationTests: Started Springboot03LoggingApplicationTests in 1.745 seconds (JVM running for 2.833) 2020-10-20 14:46:26.716 INFO 17748 --- [main] .bsSpringboot03LoggingApplicationTests: info level log. . . . . 2020-10-20 14:46:26.716 WARN 17748 --- [main] .bsSpringboot03LoggingApplicationTests: warn level log. . . . . 2020-10-20 14:46:26.716 ERROR 17748 --- [main] .bsSpringboot03LoggingApplicationTests: Error level log. . . . . Copy code

able to pass
Modify the default configuration of Spring Boot's log in the file. This file can also modify other configurations of Spring Boot. For details, please refer to the configuration of Spring Boot.

: Specify the output level of the log, you can configure the output level of the log separately for each package and class in the project;

: Specify the output path of the log;
: Specify the output name and path of the log, when
When the attributes are configured at the same time,
The configuration will not take effect;

: Specify the style of console output;

The difference in output:
(none)(none)Only output log information in the console
Specify file name(none)
Specify the name of the output log file. The name can be an exact location or relative to the current project directory.
(none)Specify the directory
Log 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 itemConfiguration content
Indicates the date and time configuration
Represents the thread name
Means to display 5 characters width from the left
Indicates that the logger name can be up to 50 characters long, otherwise it is divided by periods.
Represents log messages
Means line break

Examples of log output styles:

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n

Code example:

# Configure the output level of the log, you can configure the log output level separately for each package and class = trace # path specifies the output directory of the log, a spring folder will be created under the disk root path and in the directory Generate a spring.log file to record log information under # Do not add/then create a folder in the project directory, and generate a log output file spring.log #logging.file.path=/spring # name specifies the name of the output file And path, file location can be freely specified. When path and name are written at the same time, only name will take effect = E:/spring/demo-spring.log # Specify the log style output by the console # %d means date and time, # %thread means thread name, #% 5level: The level displays 5 characters width from the left. # %logger{50} means that the logger name can be up to 50 characters long, otherwise it is divided by periods. # %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 a log file output style # logging.pattern.file = % D-YYYY the MM-dd {} === [Thread%]% -5level === === ===% Logger%} {50% n-MSG replication Code

4.2 Specify log configuration

We can specify a configuration file for the logging framework, as long as the configuration file is placed in the classpath. SpringBoot will not use the default configuration.

Configuration files corresponding to different log frameworks:

Logging SystemCustomization
, or
JDK (Java Util Logging)
  • logback.xml
    : The configuration file will be directly recognized by the log framework;
  • logback-spring.xml
    : The logging framework does not directly load the configuration items of the log. Spring Boot parses the log analysis, and you can use the advanced profile function of Spring Boot. For more information, please refer to the previous Spring Boot configuration related content.

Note: If you use

If you still use Spring Boot's advanced Profile function, an error will be reported.

Log configuration in the official Spring Boot documentation: Spring Boot log configuration

5. Switch log frame

Spring Boot allows us to replace the default

slf4j + logback
The log frame structure can be switched to other log configuration frames. For example: we switch the log output framework to
The way.

Modify the pom.xml file:

< dependency > < groupId > org.springframework.boot </groupId > < artifactId > spring-boot-starter-web </artifactId > < exclusions > <!-- Exclude logback logging framework in SpringBoot framework--> < exclusion > < artifactId > logback-classic </artifactId > < groupId > ch.qos.logback </groupId > </exclusion > <!-- Exclude logback conversion framework in SpringBoot framework --> <exclusion > < artifactId > log4j-to-slf4j </artifactId > < groupId > org.apache.logging.log4j </groupId > </exclusion > </exclusions > </dependency > <! - log4j adaptation packages introduced to replace logback framework log4j frame -> < dependency > < the groupId > org.slf4j </the groupId > < the artifactId > SLF4J-log4j12 </the artifactId > </dependency > copy the code

In actual development, it is not recommended to switch to log4j framework. Log4j framework has performance problems. It is recommended to use logback or log4j2 logging framework.

Switch to

As a log output framework



< dependency > < groupId > org.springframework.boot </groupId > < artifactId > spring-boot-starter-web </artifactId > < exclusions > <!-- Exclude the logging starter in SpringBoot --> < exclusion > < artifactId > spring-boot-starter-logging </artifactId > < groupId > org.springframework.boot </groupId > </exclusion > </exclusions > </dependency > <! - log4j introduction of Starter -> < dependency > < the groupId > org.springframework.boot </the groupId > < the artifactId > Spring-Boot-Starter-log4j2 </the artifactId > </dependency > copy the code

Dependencies after switching to log4j2 framework