Home > Article > Backend Development > Spring Boot logging framework practice - hansonwang99's technical sharing
This article mainly shares with you the practice of Spring Boot logging framework. The code part is also very detailed. Friends in need can refer to it.
In Java applications, logs are generally divided into the following 5 levels:
ERROR Error message
WARN Warning message
INFO General information
DEBUG Debug information
TRACE Trace information
Spring Boot uses Apache’s Commons Logging as the internal logging framework, which is just a log interface , in actual applications, it is necessary to specify the corresponding log implementation for this interface.
The default log implementation of SpringBt is Java Util Logging, which is the log package that comes with the JDK. In addition, SpringBt of course also supports popular log implementations such as Log4J and Logback.
Unify the above log implementation collectively as log framework
Let’s practice it!
First add the configuration to the application.properties file:
logging.level.root=INFO
The controller part code is as follows:
package com.hansonwang99.controller; import com.hansonwang99.K8sresctrlApplication; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testlogging") public class LoggingTestController { private static Logger logger = LoggerFactory.getLogger(K8sresctrlApplication.class); @GetMapping("/hello") public String hello() { logger.info("test logging..."); return "hello"; } }
Running result
Since the log level is set to INFO, log information containing INFO and above levels will be printed
It can be seen here that many and most INFO logs come from the SpringBt framework itself, if we want to block them, we can set the log level to ERROR first, so that the INFO information of the framework itself will not be printed. Then set specific packages in the application to DEBUG level logs, so that you can only see DEBUG and above level logs in the packages you care about.
Control the log level of a specific package
Change the configuration in application.yml
logging: level: root: error com.hansonwang99.controller: debug
Obviously, change the root log level Set it to ERROR, and then set the log level of the com.hansonwang99.controller
package to DEBUG, which means: first disable all and then allow individual setting methods
Controller code
package com.hansonwang99.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testlogging") public class LoggingTestController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @GetMapping("/hello") public String hello() { logger.info("test logging..."); return "hello"; } }
Running result
##It can be seen that all the INFO level logs of the framework itself are hidden, and the logs in the specified package are printed smoothly according to the level
logging: level: root: error com.hansonwang99.controller: debug file: ${user.home}/logs/hello.log
##Using Spring Boot Logging, we found that although the log has been output to the file, a copy will still be printed in the console. We found that using
org.slf4j.Logger cannot solve this problem.
Integrate Log4J logging framework
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
file in the resources directory with the following content:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appenders> <File name="file" fileName="${sys:user.home}/logs/hello2.log"> <PatternLayout pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"/> </File> </appenders> <loggers> <root level="ERROR"> <appender-ref ref="file"/> </root> <logger name="com.hansonwang99.controller" level="DEBUG" /> </loggers> </configuration>
#And the log format is the same as pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"
Matches what is defined in the formatLog4J Further practice
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <configuration status="warn"> <properties> <Property name="app_name">springboot-web</Property> <Property name="log_path">logs/${app_name}</Property> </properties> <appenders> <console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="[%d][%t][%p][%l] %m%n" /> </console> <RollingFile name="RollingFileInfo" fileName="${log_path}/info.log" filePattern="${log_path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz"> <Filters> <ThresholdFilter level="INFO" /> <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL" /> </Filters> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!-- 归档每天的文件 --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- 限制单个文件大小 --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- 限制每天文件个数 --> <DefaultRolloverStrategy compressionLevel="0" max="10"/> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${log_path}/warn.log" filePattern="${log_path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz"> <Filters> <ThresholdFilter level="WARN" /> <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL" /> </Filters> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!-- 归档每天的文件 --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- 限制单个文件大小 --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- 限制每天文件个数 --> <DefaultRolloverStrategy compressionLevel="0" max="10"/> </RollingFile> <RollingFile name="RollingFileError" fileName="${log_path}/error.log" filePattern="${log_path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz"> <ThresholdFilter level="ERROR" /> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!-- 归档每天的文件 --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- 限制单个文件大小 --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- 限制每天文件个数 --> <DefaultRolloverStrategy compressionLevel="0" max="10"/> </RollingFile> </appenders> <loggers> <root level="info"> <appender-ref ref="Console" /> <appender-ref ref="RollingFileInfo" /> <appender-ref ref="RollingFileWarn" /> <appender-ref ref="RollingFileError" /> </root> </loggers> </configuration>
package com.hansonwang99.controller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/testlogging") public class LoggingTestController { private final Logger logger = LogManager.getLogger(this.getClass()); @GetMapping("/hello") public String hello() { for(int i=0;i<10_0000;i++){ logger.info("info execute index method"); logger.warn("warn execute index method"); logger.error("error execute index method"); } return "My First SpringBoot Application"; } }
The logs will be stored in different files according to different levels. When the log file size exceeds 2M, it will be divided into multiple files for compressed storage. Log files in the production environment It is recommended to adjust the size to 20-50MB. For more original articles by the author, please see the SF column More practical articles on SpringBt by the author are here: The practice of ElasticSearch search engine in SpringBoot Initial exploration of Kotlin+SpringBoot joint programming Related recommendations: The 8 most commonly used Java log frameworks by java programmers
Postscript
The above is the detailed content of Spring Boot logging framework practice - hansonwang99's technical sharing. For more information, please follow other related articles on the PHP Chinese website!