SpringBoot Log Framework Automatic Configuration and Principles

Posted by livepjam on Sat, 31 Aug 2019 08:49:54 +0200

1. Log Framework

Xiao Zhang; Develop a large system;

1. System.out.println("); Print key data to console; Remove?Write in a file?

2. Framework to record some runtime information of the system; Log Framework; zhanglogging.jar;

3. What are the functions of tall?Asynchronous mode?Automatic archiving?xxxx?zhanglogging-good.jar?

4. Remove the previous frame?Replace the new framework and modify the previous API; zhanglogging-prefect.jar;

5. JDBC - database driver;

Has written a unified interface layer; log facet (an abstract layer of logs); logging-abstract.jar;

Import specific log implementations into the project; our previous log framework was the abstraction layer of the implementation;

The log framework on the market;

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

Log Face (the abstraction layer of logs) Log implementation
JCL(Jakarta Commons Logging) SLF4j(Simple Logging Facade for Java) jboss-logging Log4j JUL(java.util.logging) Log4j2 Logback

Select a facade (abstraction layer) on the left and an implementation on the right.

Log Face: SLF4J;

Log implementation: Logback;

SpringBoot: The bottom level is the Spring framework, which is JCL by default; '

==SpringBoot uses SLF4j and logback; ==

2. Use of SLF4j

1. How to use SLF4j https://www.slf4j.org in the system

In future development, calls to logging methods should not directly call the implementation class of logging, but instead call the methods in the log abstraction layer.

Import the implementation jar and logback of slf4j into the system

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");
  }
}

Diagram;

Each log implementation framework has its own configuration file.After using slf4j, the configuration file is still a log implementation framework's own configuration file;

2. Legacy Issues

a(slf4j+logback): Spring(commons-logging),Hibernate(jboss-logging),MyBatis,xxxx

Unified logging, even if other frameworks work with me to unify slf4j output?

How to unify all logs in the system to slf4j;

==1, exclude other logging frameworks from the system; ==

==2, replace the old log framework with a tundish; ==

==3, we imported other implementations of slf4j==

3. SpringBoot log relationships

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

SpringBoot uses it for logging purposes;

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>

Underlying dependencies

Summary:

1), SpringBoot underlying is also logging using slf4j+logback

2), SpringBoot also replaced the other logs with slf4j;

3), Intermediate replacement package?

@SuppressWarnings("rawtypes")
public abstract class LogFactory {

    static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";

    static LogFactory logFactory = new SLF4JLogFactory();

4) If we want to introduce another framework?Do you have to remove the default log dependencies for this framework?

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>

==SpringBoot automatically adapts to all logs, and the underlying uses slf4j+logback to log. When introducing other frameworks, you only need to exclude the log framework on which this framework depends; ==

4. Log usage;

1. Default Configuration

SpringBoot helps us configure our logs by default;

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

        //Level of log;
        //From low to high trace<debug<info<warn<error
        //You can adjust the log level of the output; the log will only take effect at this level and at a later level
        logger.trace("This is trace Journal...");
        logger.debug("This is debug Journal...");
        //SpringBoot defaults to info level for us, SpringBoot default level for no specified level; root level
        logger.info("This is info Journal...");
        logger.warn("This is warn Journal...");
        logger.error("This is error Journal...");


    }
    Log output format:
        %d represents the date and time,
        %threads denotes the thread name,
        %-5level: level shows 5 characters width from left
        %logger{50} means that the logger name has a maximum of 50 characters, otherwise it is split by a period. 
        %msg: Log message,
        %n is a line break
    -->
    %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

SpringBoot Modifies the Default Configuration of Logs

logging.level.com.atguigu=trace


#logging.path=
# Generate the springboot.log log under the current project without specifying a path
# You can specify a complete path;
#logging.file=G:/springboot.log

# Create the spring folder and the log folder inside the current disk's root path; use spring.log as the default file
logging.path=/spring/log

#  Format of log output in console
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# Specify the format of log output in the file
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
logging.file logging.path Example Description
(none) (none) Output only in console
specify a filename (none) my.log Output log to my.log file
(none) Specify directory /var/log Output to the spring.log file in the specified directory

2. Specify Configuration

Put each logging framework's own configuration file under the class path; SpringBoot does not use his default configuration

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: directly identified by the log framework;

logback-spring.xml: The log framework does not directly load the log's configuration items, it is configured by SpringBoot to parse the log, and it can use SpringBoot's advanced Profile functionality

<springProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
    You can specify that a configuration only works in a certain environment
</springProfile>

For example:

<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <!--
        Log output format:
            %d represents the date and time,
            %threads denotes the thread name,
            %-5level: level shows 5 characters width from left
            %logger{50} means that the logger name has a maximum of 50 characters, otherwise it is split by a period. 
            %msg: Log message,
            %n is a line break
        -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <springProfile name="dev">
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
            </springProfile>
            <springProfile name="!dev">
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern>
            </springProfile>
        </layout>
    </appender>

If you use logback.xml as a log configuration file and also use the profile function, the following errors will occur

no applicable action for [springProfile]

5. Switch Log Framework

The log adapter of slf4j can be used for related switching.

The way 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>

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>

Topics: Java Spring SpringBoot xml log4j