This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

One, foreword

In the development of the project, the log is an essential component to record events, so we will implement and build the log framework we need accordingly in the project. There are many common logging frameworks in the market, such as JCL, SLF4J, Jboss-Logging, jUL, log4J, log4j2, LogBack, etc. How to choose? Typically, logging is constructed by a combination of abstraction layer and implementation layer.

Journal-abstraction layer Logging implementation layer
JCL (Jakarta Commons LoggingSLF4j (Simple LoggingFacade for Java)jboss-logging Log4j JUL (java.util.logging) Log4j2Logback
# 2. Analysis
Let’s start with log implementation analysis,
  1. JUL (java.util.logger) has been abandoned because of its simple design and insufficient support for application system development.
  2. Log4j is a very popular logging implementation, but it is currently upgraded to LogBack. The author states that LogBack has many advantages over Log4j. Logback. Qos. Ch/index. HTML.
  3. Log4j2 is a powerful, complex design that is not supported by many open source frameworks and is easy to stomp on. It is not recommended, and LogBack’s performance is sufficient to support it. So the logging implementation we use is logback.
  4. Logback and LOG4J are written by the same author and are an upgraded version of log4j with better performance!

== SpringBoot also uses SLF4j+logback logging framework ==

3. Issues left over from history

Development framework Corresponding logging framework
springboot slf4j+logback
Spring commons-logging
Hibernate jboss-logging
Given that there are so many Java development frameworks, each of which uses a different logging framework, how can we unify logging, even if other frameworks join me in using SLF4J for output?
The steps to unify all logs in the system to SLf4J are as follows:
  1. Exclude other logging frameworks in the system;
  2. Replace the old logging framework with a tundish;
  3. We import the other implementations of SLF4J

Springboot log relationship

SpringBoot uses it for logging; < the dependency > < groupId > org. Springframework. Boot < / groupId > < artifactId > spring ‐ boot ‐ starter ‐ logging < / artifactId > </dependency>Copy the code

Underlying relationship dependency diagram:2) SpringBoot replaces all other logs with SLF4J (using an intermediate replacement package);

What if we were to introduce other frameworks? Must the framework’s default logging dependency be removed?

The Spring framework uses commons-logging:

<dependency>        
		<groupId>org.springframework</groupId>            
		<artifactId>Spring ‐ core</artifactId>            
		<exclusions>            
				<exclusion>                
				<groupId>Commons ‐ logging</groupId>                    
				<artifactId>Commons ‐ logging</artifactId>                    
				</exclusion>                
		</exclusions>            
</dependency> 
Copy the code

==SpringBoot automatically ADAPTS all logging, and slF4J +logback is used to record logging. When introducing other frameworks, you only need to exclude the logging framework that this framework depends on. ==

Four, the use of logs

SpringBoot has configured logging for us by default, so I can write the following code directly in the SRC /test package’s test class:

package com.ratel.springboot;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootLoggerApplicationTests {

	/ / recorder
	Logger logger = LoggerFactory.getLogger(getClass());
	@Test
	public void contextLoads(a) {
		//System.out.println();

		// Log level;
		// Trace 
		// Can adjust the output log level; Logs will only take effect at this level at a later high level
		logger.trace("This is the trace log...");
		logger.debug("This is the debug log...");
		//SpringBoot uses the info level by default. If no level is specified, SpringBoot uses the default level. The root level
		logger.info("This is info log...");
		logger.warn("This is a WARN log...");
		logger.error("This is error log..."); }}Copy the code

Log output format:

%d indicates the date and time, %thread indicates the thread name, %‐5level: level displays 5 characters in width from the left. %logger{50} indicates that the logger name is a maximum of 50 characters, otherwise split by periods. % MSG: log message, %n: newline % D {YYYY ‐MM‐ DD HH: MM: ss.sss} [%thread] %‐5level %logger{50} ‐ % MSG %nCopy the code

SpringBoot changes the default configuration of logging.

Method 1: Directly modify the application. Yml or application. Properties configuration file

With the application. Properties file:

Logging.level.com.atguigu=trace # logging. The path = # does not specify a path generated under the current project springboot. The log log # can specify the full path; File =G:/springboot.log =G:/springboot.log Path =/spring/log # The format of the log output on the console is logging.pattern.console=%d{YYYY ‐MM‐dd} [%thread] %‐5level % % % logger {50} ‐ MSG n # specified file format of the log output logging. The pattern. The file = % d {yyyy MM ‐ ‐ dd} = = = [% thread] ‐ level 5 = = = = = = % % logger {50} = = = = %msg%nCopy the code

Method 2: Specify the configuration

Just delegate each logging framework’s own configuration file to the classpath; SpringBoot does not use its default configurationFor example, place it as shown in the following image:logback.xml: is recognized directly by the logging framework; orlogback-spring.xml: The logging framework does not load the log configuration items directly. SpringBoot parses the log configuration. You can use the advanced Profile function of SpringBoot (recommended).

<springProfile name="staging"><! ‐ configuration to be enabled when the "staging" profile is active ‐‐> Can specify that a configuration can only be performed in one environment (DEV, test, PROD, etc.)</springProfile>
Copy the code

Such as:

<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"><! ‐ log output format: % D indicates the date and time, % Thread indicates the thread name, %‐5level: level displays 5 characters from the left. %logger{50} indicates the maximum length of the logger name is 50 characters. Otherwise, the logger name is divided by periods. % MSG: log message, %n newline ‐‐><layout class="ch.qos.logback.classic.PatternLayout">
            <springProfile name="dev">
                <pattern>% d {yyyy MM ‐ ‐ dd HH: MM: ss. The SSS} ‐ ‐ ‐ ‐ > [% thread] ‐ ‐ ‐ ‐ 5 level > % % logger {50} ‐ MSG % % n</pattern>
            </springProfile>
            <springProfile name=! "" dev">
                <pattern>% d {yyyy MM ‐ ‐ dd HH: MM: ss. The SSS} = = = = thread] [% = = = = 5 level % % ‐ logger {50} ‐ MSG % % n</pattern>
            </springProfile>
        </layout>
    </appender>
Copy the code

If logback.xml is used as the log configuration file and the profile function is used, the following error occurs:

no applicable action for [springProfile]
Copy the code

6. Switching logging Frameworks (not recommended)

You can switch according to slF4J’s log adaptation diagram.

Slf4j +log4j;

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>Spring ‐ boot ‐ starter ‐ web</artifactId>
  <exclusions>
    <exclusion>
      <artifactId>Logback ‐ classic</artifactId>
      <groupId>ch.qos.logback</groupId>
    </exclusion>
    <exclusion>
      <artifactId>Log4j ‐ over ‐ slf4j</artifactId>
      <groupId>org.slf4j</groupId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>Slf4j ‐ log4j12</artifactId>
</dependency>
Copy the code

Switch to log4j2:

<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>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>Spring ‐ boot ‐ starter ‐ log4j2</artifactId>
</dependency>
Copy the code

This article sample code address: github.com/Dr-Water/sp…