Version:
-
Spring Boot 2.1.5. RELEASE
-
Maven 3.2.5
-
jdk1.8
1. The logging framework I choose:
- Logging facade (abstraction layer): SLF4J
- Log implementation: Logback
Spring Boot: The underlying layer is the Spring framework, which is JCL by default;
Spring Boot uses SLF4j and Logback
2. Use SLF4j
1) How to use SLF4j in your system
SLF4j’s official manual
Development, logging method invocation, not directly call logging implementation class, but call logging abstraction layer method;
- Import the SLF4J JAR and logback implementation JAR
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
SLF4j with other logging frameworks:
2) Legacy issues
Although I use slF4j & Logback, others such as the Commons-logging framework used by the Spring framework, Hibernate uses the Jboss-Logging framework, etc., it’s too messy, so we need to unify logging, even if other frameworks need to join me in using SLF4J for output;
The official sketch:
Logic:
- 1. Exclude other log frameworks.
- 2. Replace the original logging framework with a tundish (the one in red is the tundish);
- 3. Import other implementations of SLF4J
3. Relationship between Spring Boot logs
This is actually the package that this depends on:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<version>2.1.5. RELEASE</version>
<scope>compile</scope>
</dependency>
Copy the code
Right-click under the POM file:
All SpringBoot dependencies, we only look at logging:
I used Spring Boot version 2.1.5. During the learning process, the author found that the version in the teacher’s video I watched was different from mine.
This is the teacher’s version:
Obviously not like me, but Spring has definitely upgraded its bottom layer;
Not exactly an upgrade, but a transformation that removes the JCL framework, which was last updated in 2014 and is clearly outdated
Slf4j does have the same functionality as springBoot1. x, but does not have the same functionality as my 2.x version.
Summary:
- 1. The bottom layer of SpringBoot is also slF4J +logback for logging;
- 2.SpringBoot also replaces all other logs with slf4J;
- 3. Intermediate replacement package;
Intermediate replacement package illustration:
4) If we introduce another framework, we must remove this framework’s default logging dependency!
The Spring framework’s default logging framework is Commons -logging;
When Spring Boot introduces the Spring core JAR, it removes the log JAR.
Spring Boot automatically ADAPTS all logging, and slF4J + Logback logging is used at the bottom. When introducing other frameworks, you only need to exclude the logging dependent on this framework
4. Log usage
The test class:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootLoggingApplicationTests {
// The logger
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void contextLoads(a) {
// Log level
// Trace < debug < info < warn < error from low to high
logger.trace("This is the trace log...");
logger.debug("This is debug debug log...");
logger.info("This is info log..");
logger.warn("This is a WARN log...");
logger.error("This is the error error log."); }}Copy the code
Running output:
2019-07-02 19:22:35.980 INFO 8404- [the main] C.C.S.S pringBootLoggingApplicationTests: this is the info log..2019-07-02 19:22:35.981 WARN 8404- [the main] C.C.S.S pringBootLoggingApplicationTests: this is a warn log...2019-07-02 19:22:35.981 ERROR 8404- [the main] C.C.S.S pringBootLoggingApplicationTests: this is the error error logCopy the code
The default SpringBoot log level is INFO, so only info and logs larger than info are output.
Open my YML configuration file:
logging:
level:
com.carson: trace
Copy the code
Set all my packages under com. Carson to the trace log level
Output result:
The 2019-07-02 19:29:17. 7076-406 TRACE [main] C.C.S.S pringBootLoggingApplicationTests: this is the TRACE log.. The 2019-07-02 19:29:17. 7076-407 the DEBUG [main] C.C.S.S pringBootLoggingApplicationTests: this is the DEBUG DEBUG log.. The 2019-07-02 19:29:17. 7076-407 the INFO [main] C.C.S.S pringBootLoggingApplicationTests: this is the INFO log.. The 2019-07-02 19:29:17. 7076-408 WARN [main] C.C.S.S pringBootLoggingApplicationTests: this is a WARN log... The 2019-07-02 19:29:17. ERROR 408-7076 [main] C.C.S.S pringBootLoggingApplicationTests: this is the ERROR of the ERROR logCopy the code
4.1 Configuration File Details:
logging.level.com.carson= trace # path: Path = F:/spring/log # file: File = F:/springboot.log # pattern.console: Console = %d{YYYY ‐MM‐ DD} === [%thread] === %‐5level ==== %logger{50} ==== % MSG % N # pattern.file File = % D {YYYY ‐MM‐ DD} === [%thread] === %‐5level ==== %logger{50} ==== % MSG %nCopy the code
4.2 Specifying The Configuration
The logging framework | The file name |
---|---|
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 |
The above is from the official SpringBoot document, which is the name he requested, and SpringBoot will read it
- logback-spring.xml :
<?xml version="1.0" encoding="UTF-8"? >
<! -- scan: When this property is set to true, the configuration file will be reloaded if it changes. The default value is true. ScanPeriod: indicates the interval for checking whether the configuration file is modified. If no time unit is given, the default unit is ms. This parameter takes effect when scan is true. The default interval is 1 minute. Debug: When this attribute is set to true, internal logback logs are displayed to view the running status of logback in real time. The default value is false. -->
<configuration scan="false" scanPeriod="60 seconds" debug="false">
<! Define log root directory -->
<property name="LOG_HOME" value="/app/log" />
<! Define log file name -->
<property name="appName" value="atguigu-springboot"></property>
<! - ch. Qos. Logback. Core. ConsoleAppender said console output -- -- >
<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>
<! -- Scroll to log file, first log to specified file, when a condition is met, log to other files -->
<appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<! -- Specify log file name -->
<file>${LOG_HOME}/${appName}.log</file>
<! TimeBasedRollingPolicy determines the behavior of the RollingFileAppender when scrolling occurs, involving file movement and renaming. TimeBasedRollingPolicy: the most commonly used rollingpolicy. It is responsible for both rolling and starting rolling based on time. -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<! %d{YYYY-MM-DD} : the file is scrolled by day % I: the file is scrolled by I when the file size exceeds maxFileSize -->
<fileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
<! -- Optional node that controls the maximum number of archived files that can be retained, and deletes old files if the number exceeds it. If daily scrolling is set and maxHistory is 365, only the files of the last 365 days are saved and the old files before that are deleted. Note that when old files are deleted, directories created for archiving are also deleted. -->
<MaxHistory>365</MaxHistory>
<! - when a log file over maxFileSize size is specified, according to the above mentioned to the log file % I roll Pay attention to the configuration SizeBasedTriggeringPolicy rolling according to the file size is not impossible to achieve, You must configure timeBasedFileNamingAndTriggeringPolicy -- -- >
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<! -- Log output format: -->
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [ %thread ] - [ %-5level ] [ %logger{50} : %line ] - %msg%n</pattern>
</layout>
</appender>
<! Logger is mainly used to store log objects. You can also define log types and log levels. Name: indicates the matched logger type prefix, that is, the first half of the package level: The log level to log, including TRACE < DEBUG < INFO < WARN < ERROR additivity: depends on whether the children-Logger outputs using an appender configured for rootLogger. False: True: Indicates that both logger appender-ref and rootLogger appender-ref are valid.
<! -- hibernate logger -->
<logger name="com.atguigu" level="debug" />
<! -- Spring framework logger -->
<logger name="org.springframework" level="debug" additivity="false"></logger>
<! -- Root is parent to logger, default to root if there is no specific definition. Each class corresponds to only one logger, either the defined logger or root. The key is to find this logger. Then determine the logger's appender and level. -->
<root level="info">
<appender-ref ref="stdout" />
<appender-ref ref="appLogAppender" />
</root>
</configuration>
Copy the code
Make a copy of the above configuration and put it in the resources of the project, or make a custom configuration.
-
Logback.xml: directly recognized by the logging framework
-
But if you use the logback-spring.xml name (recommended): The logging framework does not load the log configuration items directly, and SpringBoot parses the log so you can use one of SpringBoot’s advanced features
<springProfile name="prod">
<! -- ProD environment -->
</springProfile>
<springProfile name="dev | prod">
<! -- dev and prod both execute -->
</springProfile>
<springProfile name=! "" dev">
<! -- If not dev environment -->
</springProfile>
Copy the code
That’s what we saw in the configuration file:
<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
You can configure one in your YML or Properties:
spring.profiles.active= prod Copy the code
To set up the operating environment
4.3 use log4j
SpringBoot does a few things for us:
Name | Description | Pom |
---|---|---|
spring-boot-starter-jetty |
Starter for using Jetty as the embedded servlet container. An alternative to spring-boot-starter-tomcat |
Pom |
spring-boot-starter-log4j2 |
Starter for using Log4j2 for logging. An alternative to spring-boot-starter-logging |
Pom |
spring-boot-starter-logging |
Starter for logging using Logback. Default logging starter | Pom |
spring-boot-starter-reactor-netty |
Starter for using Reactor Netty as the embedded reactive HTTP server. | Pom |
spring-boot-starter-tomcat |
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web |
Pom |
spring-boot-starter-undertow |
Starter for using Undertow as the embedded servlet container. An alternative to spring-boot-starter-tomcat |
Pom |
For example, if I want to use log4j2, I will first exclude the default spring-boot-starter-logging.
- Then in the POM file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>2.1.1. RELEASE</version>
</dependency>
Copy the code
Import log4j2 package;
- Create a log4j configuration file in Resources with the same name:
Content:
### set log levels ### log4j.rootLogger = debug , stdout , D , Output to the console E # # # # # #. Log4j appenders. Stdout = org.. Apache log4j. ConsoleAppender log4j. Appender. Stdout. Target = System. Out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = % d {ABSOLUTE} = = = = = % 5 p % c {1} : % L - % m % n output to the log file # # # # # # # # log4j. Appender. D = org.. Apache log4j. DailyRollingFileAppender #log4j.appender.D.File = logs/log.log #log4j.appender.D.Append = true #log4j.appender.D.Threshold = DEBUG ## . The DEBUG output level above log # log4j appenders, D.l ayout = org.. Apache log4j.. # PatternLayout log4j appenders. D.l ayout. ConversionPattern = - % d {MM - dd yyyy - HH: MM: ss} [% t: % r] - [p] % % m % n # # # # # save exception information to separate file # # # # log4j. Appender. D = Org, apache log4j. # DailyRollingFileAppender log4j. Appender. D.F ile = logs/error log. # # # abnormal log filename log4j appenders. Da ppend = True. # log4j appenders. Which hreshold = ERROR # # only output ERROR level above log!!!!!! #log4j.appender.D.layout = org.apache.log4j.PatternLayout #log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%nCopy the code
In other words, if you want to introduce other logging frameworks, you can simply remove the previous framework and then introduce the new one
Personal blog: aaatao66.github. IO /