Detailed explanation of the configuration log framework in SpringBoot (nanny-level tutorial)

This article mainly describes the configuration log framework in the SpringBoot framework, which has a certain reference learning value for everyone's study or work. Friends who need it, let's learn together with the editor below.

Let's talk briefly about the log framework first

The log framework can help us complete workbench output, asynchronous log recording, and automatic archiving (output log to file) in the project. In the gradual formation of the framework, the log framework is divided into an abstraction layer and an implementation layer.

The so-called abstraction layer can also be called the unified interface layer. Before, we all implemented the interface layer directly in the code to complete log processing, but if the interface layer changes, the degree of change is very large, which can also be understood as The code is highly coupled.

In order to reduce the degree of code coupling, it is split into two layers. Now our log implementation can directly import the related jar packages of the interface layer and the log implementation layer. Basically, you can quickly implement log processing without writing any code at all.

Frame selection

There are many logging frameworks on the market. JUL (java.util.logging), JCL (Apache Commons Logging), Log4j, Log4j2, Logback, SLF4j, jboss-logging, etc. Spring Boot uses JCL in the content of the framework. Spring-boot-starter-logging adopts the form of slf4j+logback . Spring Boot can also automatically adapt (jul, log4j2, logback) and simplify the configuration.

The facade of this piece refers to the interface layer, and on the right is the implementation class.
Choose a facade (abstraction layer) on the left and an implementation on the right;

Log facade: SLF4J;
log implementation: Logback;

For the general log facade (interface layer), we will use SLF4J. Reason: JCL has not been updated for a long time. The last update was in 2014. The general specific framework of jboss will be used, so it is not applicable to us.

Logback is generally used in the implementation layer. The reason: JUL is relatively no good. SLF4J, Log4j and Logback are written by the same person, and Logback is an upgraded version of Log4j. Although Log4j2 is also perfect, it is too perfect, and many frameworks are not adapted.

Simple use of Slf4j

In actual development, we generally do not directly remove the implementation class, but remove the method of the interface layer.

Import the slf4j jar and the logback implementation jar into the system. Spring-boot-starter-web comes with spring-boot-starter-web itself, so there is no need to import the jar package.

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

Each log implementation framework has its own configuration file. After using slf4j, the configuration file is still made into the configuration file of the log implementation framework itself

Configuration steps in SpringBoot

1. Exclude other framework log packages

In general projects, once we choose a log implementation framework, we will use this uniformly. Many of the frameworks we use will have their own log framework. At this time, we need to exclude packages and exclude their own log packages. , Avoid jar package conflicts.

Doesn't it report an error if you exclude the packet?
SLF4j provides us with intermediate packages, these intermediate packages are a conversion function, based on the replacement of his original log framework, and to ensure that the framework can run normally. These replacement packages were added when spring-boot-starter-web was introduced . The function of these two packages is that the log4j and jul frameworks will all use slf4j uniformly , so all we need to do is to exclude the jar packages that come with those frameworks. Don't let him in.
Insert picture description here
pom example:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient-cache</artifactId>
	<!-- 依从 spring-boot 管理版本 -->
	<version>4.5.2</version>
	<scope>compile</scope>
	<exclusions>
		<exclusion>
			<!-- 使用 jcl-over-slf4j 代替 -->
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>

2. Understand the default configuration

Some default configurations will be configured for us in the springboot automatic assembly. Even if we use the logging framework without any configuration, he can also complete some basic functions for us.

Under this jar package, you can see the default configuration
Insert picture description here
Insert picture description here

It can be seen from here that his default configuration level is info.

3. Modify the default value through the global configuration

By default, Spring Boot will only output logs to the console.
If you don't need complicated functions, you just want to output the same log in a file.
Just add the following configuration in application.properity:

#在当前磁盘的根路径下创建log文件夹和里面的MyProject文件夹;使用 spring.log 作为默认文件
logging.path=/log/MyProject

# 可以指定完整的路径;不指定磁盘路径在当前项目下生成springboot.log日志
logging.file=G:/springboot.log

#设置具体包的日志级别(这里将与MyBatis相关的mapper包设置为debug级别,效果就是在日志中输出sql语句)
logging.level.cn.gzl.Mapper=debug

Log output format:

%d means the date and time,
%thread means the thread name,
%-5level: the level is displayed from the left with 5 characters width
%logger{50} means the logger name has a maximum of 50 characters, otherwise it is divided by periods.
%msg: log message,
%n is a newline character

The above is the meaning of the log output format identifier: after understanding its meaning, we can modify the console information we want by adding configuration to the global configuration.

# 在控制台输出的日志的格式 
logging.pattern.console=%d{
    
    yyyy‐MM‐dd} [%thread] %5level %logger{
    
    50}%msg%n 
# 指定文件中日志输出的格式 
logging.pattern.file=%d{
    
    yyyy‐MM‐dd} === [%thread] === %5level === %logger{
    
    50} ==== %msg%n

4. Specify the configuration file

Just put each log framework's own configuration file under the classpath; SpringBoot does not use his default configuration

We use logback, generally use the following two

logback.xml: It is directly recognized by the logging framework;
logback-spring.xml: The logging framework does not directly load the configuration items of the log. The log configuration is parsed by SpringBoot, and the advanced profile function of SpringBoot can be used.

<springProfile name="staging"> 
	<!‐‐ configuration to be enabled when the "staging" profile is active ‐‐> 
	可以指定某段配置只在某个环境下生效 
</springProfile>

Complete logback-spring.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">
    <include resource="org/springframework/boot/logging/logback/base.xml" />

	<contextName>ph-logback</contextName>
	<property name="log.path" value="c:/logback/logback.log" />

	<!-- 输出的控制台 -->
	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>INFO</level>
		</filter>
		<encoder>
			<pattern>%d{
    
    HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{
    
    36} - %msg%n
			</pattern>
		</encoder>
	</appender>

	<!-- 输出到文件 -->
	<appender name="file"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<!--日志名,用到了上面配置的路径-->
		<file>${
    
    log.path}</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
			<fileNamePattern>${
    
    log.path}.%d{
    
    yyyy-MM-dd}.%i.log</fileNamePattern>
			<!-- 单个文件最大100M -->			
			<maxFileSize>100MB</maxFileSize>
			<!-- 保留30天的日志 -->
			<maxHistory>30</maxHistory>
		</rollingPolicy>

		<encoder>
			<pattern>%date %level [%thread] %logger{
    
    36} [%file : %line] %msg%n
			</pattern>
		</encoder>
	</appender>
	
	<!-- 开发环境 -->
	<springProfile name="dev">
		<logger name="com.xjgx" level="INFO"/>
	</springProfile>
	
	<!-- 生产环境 -->
	<springProfile name="prod">
		<logger name="com.xjgx" level="ERROR"/>
	</springProfile>

	
	<!-- 日志级别 -->
	<root level="info">
		<appender-ref ref="console" />
		<appender-ref ref="file" />
	</root>
	
	<!--设置具体包的隔离级别-->
    <logger name="com.xjgx.domain.mapper" level="DEBUG"></logger>
    <logger name="com.xjgx.domain.slave.mapper" level="DEBUG"></logger>

 </configuration>

Guess you like

Origin blog.csdn.net/weixin_43888891/article/details/111134602