Three, logs,

1. Logging framework

Xiao zhang; Develop a large system;

1, System. Out. Println (” “); Print key data on the console; Get rid of? Write it in a file?

2. Framework to record some runtime information of the system; Logging framework; Zhanglogging. Jar;

3. How many functions are there? Asynchronous mode? Automatic filing? XXXX? Zhanglogging – good. Jar?

4. Remove the previous frame? Replace with a new framework and re-modify the previous related API; Zhanglogging – prefect. Jar;

5. JDBC — database driver;

Write a unified interface layer; Logging facade (an abstraction layer of logging); Logging – the abstract. The jar;

Just import a concrete logging implementation into the project; Our previous logging frameworks were an abstraction layer for implementation;

Logging frameworks on the market;

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

Log facade (log abstraction layer) The logging implementation
JCL (Jakarta Commons Logging)SLF4j (Simple Logging Facade for Java)jboss-logging Log4j JUL (java.util.logging) Log4j2Logback

Choose a facade (abstraction layer) on the left and an implementation on the right;

Log facade: SLF4J;

Log implementation: Logback;

SpringBoot: Underneath is the Spring framework, which is JCL by default; ‘

SLF4j and Logback are selected for SpringBoot.

2. Use SLF4j

1. How to use SLF4j in your systemwww.slf4j.org

In future development, logging methods should not be called directly to the logging implementation class, but to call methods in the logging abstraction layer;

Import SLF4J jar and logback implementation JAR 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"); }}Copy the code

In the figure;

Each logging implementation framework has its own configuration file. With SLF4J, the configuration file remains the logging 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 join me in using SLF4J for output?

[Failed to save external link image, the source site may have anti-theft mechanism, it is recommended to save the image and upload it directly (img-PDU5ZSB9-1597122459215)(images/ leglegacy. PNG)]

How to unify all logs in the system to SLF4J;

1. Exclude other log frameworks in the system;

2. Replace the original logging framework with a tundish;

3. We import the other implementations of SLF4J

3. SpringBoot log relationship

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

SpringBoot uses it for logging;

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

Underlying dependencies

Conclusion:

1) At the bottom of SpringBoot, slF4J + Logback is also used for logging

2) SpringBoot also replaces all 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();
Copy the code

4) What if we 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 can automatically adapt all logging, and the underlying use of SLF4J +logback logging, the introduction of other frameworks, just need to rely on the framework of the logging framework can be excluded;

4. Log usage;

1. Default configuration

SpringBoot has configured logging for us by default;

	/ / 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: indicates the level. The width is 5 characters from the left. % Logger {50} indicates that the maximum length of the logger name is 50 characters. -> %d{YYYY-MM-DD HH: MM :ss.SSS} [%thread] %-5level %logger{50} - % MSG %nCopy the code

SpringBoot modifies the default log configuration

logging.level.com.atguigu=trace


#logging.path=
Springboot. log is generated in the current project without specifying a path
The full path can be specified.
#logging.file=G:/springboot.log
Create the spring folder and log folder in the root path of the current disk. Use spring.log as the default file
logging.path=/spring/log
The format of the log output on the console
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# specify the format of the log output in the file
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
Copy the code
logging.file logging.path Example Description
(none) (none) Output only at the console
Specify file name (none) my.log Output logs to the my.log file
(none) The specified directory /var/log To the spring.log file in the specified directory

2. Specify the configuration

Just delegate each logging framework’s own configuration file to the classpath; SpringBoot does not use its 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: is recognized directly by the logging framework;

Logback-spring. XML: The log framework does not load the log configuration items directly. SpringBoot parses the log configuration and uses the advanced Profile function of SpringBoot

<springProfile name="staging">
    <! -- configuration to be enabled when the "staging" profile is active -->You can specify that a certain configuration takes effect only in a certain environment</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: indicates the level. The width is 5 characters from the left. % Logger {50} indicates that the maximum length of the logger name is 50 characters. % MSG: log message, %n: newline -->
        <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>
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]

5. Switch the logging framework

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