SpringBoot entry to the master :( five) SpringBoot integrated logging framework

Here Insert Picture Description

Foreword

It logs in a very critical part of application development, experienced engineers can rely on past experience to determine where to print the log, print the log at what level, so it can online when problems occurred quickly locate and solve problems , operation and maintenance costs greatly reduce application

text

Logging framework

frame

Java has a lot of maturity in the framework of logs, such as

  • JUL (java.util.logging)
  • Laog4j
  • Log4j2
  • Logback

There are also two log to achieve a unified framework,

  • JCL (Jakarta Commons Logging)
  • SLF4j (Simple Logging Facade for Java )

Different frame above the log, this is only a two frame facade, and no log frame specific implementation, the interface can be considered as the log frame

Spring Framework is the JCL default, and SpringBoot its packaging, using a logging framework SLF4j

SLF4j use

During development, we should not use the log call log directly implemented directly, but abstraction layer logging method should be used, so that when we want to switch logging framework, will be more flexible
SLF4j of use, we can LSLF4j official website of view, the official website provides a picture to us to illustrate the use
Here Insert Picture Description
we can see from the figure, SLF4j integration logback very convenient, directly logback jar package can be imported, but because of the time before the emergence of log4j still SLF4j , it is not adapted log4j, so we need an adaptation layer, an adaptation layer implemented SLF4j method, a method called is log4j; the same can use an adapter is required JCL

Implementation framework Each log has its own configuration file. After using slf4j, profiles made of logs or implementation framework itself profile;

Other logging framework convert slf4j

Each frame integration time, because each frame using different logging frameworks, such as Spring uses commons-logging, Hibernate using jboss-logging, then how unified logging it?
Unified logging, even though other unified framework and I use slf4j output?

slf4j official website to provide a method, the following picture
Here Insert Picture Description

How to get all the logs systems are unified to slf4j

  1. The other system logging framework to be excluded;

  2. A tundish to replace the original logging framework (alternative tundish exclude logging framework, and use the same frame packet logging);

  3. We import Other implementations slf4j

SpringBoot log relationship

SpringBoot a new project, take a look at SpringBoot how to configure the log files
Here Insert Picture Description
we can see, we have introduced the spring-boot-starter-webreferences spring-boot-starter, but spring-boot-starterthey quoted spring-boot-starter-logging
SpringBoot use spring-boot-starter-loggingto do the logging;

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

The underlying dependencies
Here Insert Picture Description

to sum up:

1. SpringBoot underlayer is used slf4j + logback manner log

2. SpringBoot also the other logs are replaced with slf4j;

3. Replace the middle bag?
Here Insert Picture Description
Alternatively the intermediate package and replaced from the package to the package name exactly the same as the class name, the only different is realized, implemented using slf4j
such jcl-over-slf4j package is commons.logging, but when actually implemented with SLF4JLogFactory

@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 other frameworks? This framework must take the default log depends removed out?

Spring frame for example, are commons-logging, SpringBoot carried exclusion

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

SpringBoot log configuration

SpringBoot help us configure the default log; used as follows:

default allocation

SpringBoot default log configuration are in defaults.xml
Here Insert Picture Description

Log Level

	//记录器
	Logger logger = LoggerFactory.getLogger(getClass());
	@Test
	public void contextLoads() {	
		logger.trace("这是trace日志...");
		logger.debug("这是debug日志...");
		logger.info("这是info日志...");
		logger.warn("这是warn日志...");
		logger.error("这是error日志...");
	}

Log level from low to high as trace<debug<info<warn<erroryou can adjust the output level of the log; the log will only take effect at a later high level at this level
SpringBoot default to us using the info level, it does not specify the level of default specified level with SpringBoot : root level

Log Format

    日志输出格式:
		%d表示日期时间,
		%thread表示线程名,
		%-5level:级别从左显示5个字符宽度
		%logger{50} 表示logger名字最长50个字符,否则按照句点分割。 
		%msg:日志消息,
		%n是换行符

    %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

SpringBoot modify the default configuration logs

logging.level.com.atguigu=trace


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

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

#  在控制台输出的日志的格式
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
logging.file logging.path Example Description
(none) (none) Only output in the console
Specify the file name (none) my.log Output log file to my.log
(none) Specified directory / Var / log Spring.log output to a file in the specified directory

Directed Placement

Each log on to the framework of the decentralization of their class path configuration files; SpringBoot not use his default configuration of the

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: logging framework directly be identified;

spring.xml-logback : logging framework is not loaded directly log configuration items by SpringBoot parsing log configuration, you can use SpringBoot advanced features Profile

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

Such as:

<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <!--
        日志输出格式:
			%d表示日期时间,
			%thread表示线程名,
			%-5level:级别从左显示5个字符宽度
			%logger{50} 表示logger名字最长50个字符,否则按照句点分割。 
			%msg:日志消息,
			%n是换行符
        -->
        <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 log configuration file, also use the profile functions, you will have the following error

no applicable action for [springProfile]

Switching logging framework

It may be adapted according to FIG slf4j log, the associated switch;

slf4j + log4j manner;

<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>
Published 40 original articles · won praise 9 · views 20000 +

Guess you like

Origin blog.csdn.net/aawmx123/article/details/102807802