4

Three, the log of the SpringBoot framework

 2 years ago
source link: https://blog.birost.com/a?ID=00000-0b6a187c-cde4-4062-a63b-0bd773c5100e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

xxxlogging.jar

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

xxxlogging-update.jar
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)

logging-abstract.jar

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 toIntroductionJCL (Jakarta Commons Logging)Log facadeA general logging API provided by ApacheSLF4j(Simple Logging Facade for Java)Log facadeSLF4J provides a unified logging interfacejboss-loggingLog facadejboss-logging is a logging framework similar to slf4jLog4j(Log for java)Log implementationAn excellent open source logging framework from the Apache FoundationJUL(java.util.logging)Log implementationLog output provided in JDKLog4j2Log implementationThe upgraded version of Log4J launched by the Apache Foundation, which supports plug-in structureLogbackLog 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); logger.info( "Hello World" ); } } Copy code

  • We only import

    slf4j-api.jar
    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

    slf4j-api.jar
    logback-classic.jar
    logback-core.jar
    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

    slf4-api.jar
    log4j.jar
    The package also needs to rely on the adaptation package
    slf4j-log412.jar

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

package

jcl-over-slfj4.jar
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

pom.xml
Imported
spring-boot-starter-web
rely;
< Dependency > < the groupId > org.springframework.boot </the groupId > < the artifactId > Spring-Boot-Starter-Web </the artifactId > </dependency > copy the code
spring-boot-starter-web
Included in dependency
spring-boot-stater
rely;
< dependency > < groupId > org.springframework.boot </groupId > < artifactId > spring-boot-starter </artifactId > < version > 2.3.4.RELEASE </version > < scope > compile </scope > </dependency > copy code
spring-boot-stater
Included in dependency
spring-boot-starter-logging
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
spring-boot-starter-logging

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

pom.xml
The dependency point of the parent class is written in
spring-boot-starter-parent-xxx.pom
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
spring-boot-starter-parent-xxx.pom
Specify the dependency packages that reference all frameworks in Spring Boot
spring-boot-dependencies.pom
< 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
spring-boot-dependencies.pom
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,

pom.xml

Used in the file

<exclusion></exclusion>

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

slf4j
frame;

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

slf4j
Methods;

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

slf4j

with

logback

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
    trace
    Level and
    debug
    The log of the level will not be output;
  • The default log output level of Spring Boot is

    level( level);

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 logger.info( "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

application.properties
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.
logging.level
: 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;
logging.file.path
: Specify the output path of the log;
logging.file.name
: Specify the output name and path of the log, when with When the attributes are configured at the same time, The configuration will not take effect;
logging.pattern.console
: Specify the style of console output;
logging.file.path
with
logging.file.file
The difference in output:
logging.file.name
logging.file.path
ExampleDescription(none)(none)Only output log information in the consoleSpecify file name(none)
my.log
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
/var/log
Output
spring.log
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 contentIndicates the date and time configuration

%thread
Represents the thread name
%-5level
Means to display 5 characters width from the left
%logger{50}
Indicates that the logger name can be up to 50 characters long, otherwise it is divided by periods.Represents log messagesMeans 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 logging.level.cn.bruce = 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 logging.file.name = 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

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
    : 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

logback.xml
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
slf4j+log4j
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

log4j2
As a log output framework

modify

pom.xml
file

< 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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK