In Java applications, logs are generally divided into the following 5 levels:
Spring Boot uses Apache's Commons Logging as the internal logging framework. It is just a log interface. In actual applications, it is necessary to specify the corresponding log implementation for this interface.
SpringBt's default log implementation is Java Util Logging, which is a log package built into JDK. In addition, SpringBt also supports very popular log implementations such as Log4J and Logback.
The above log implementations are collectively referred to as log frameworks
Let’s practice it below!
Using Spring Boot Logging Plugin
First add configuration to the application.properties file:
logging.level.root=INFO
The controller 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 results
Since the log level is set to INFO, log information containing INFO and above will be printed out
As can be seen here, most of the 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 the specific package in the application to a DEBUG level log, so that you can only see the DEBUG level logs in the package you are concerned about.
Controls the log level of a specific package
Change the configuration in application.yml
logging: level: root: error com.hansonwang99.controller: debug
It is obvious that the root log level is set to ERROR, and then the log level of com.hansonwang99.controller package is set to DEBUG, which means: first prohibiting all settings and then allowing individual settings.
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 results
It can be seen that the framework itself has all INFO-level logs hidden, and the logs in the specified package are successfully printed according to the level.
Output logs to a file
logging: level: root: error com.hansonwang99.controller: debug file: ${user.home}/logs/hello.logRunning results
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
Integrated Log4J log framework
Add dependencies in pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-b oot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
Add the log4j2.xml file in the resources directory, the content is as follows:
<?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,SS} %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>The other code remains the same
Running the program found that the console has no log output, and there is content in the hello2.log file, which is in line with our expectations:
And the log format matches the definition in pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n" format
Log4J takes further practice
pom.xml configuration:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-b oot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
log4j2.xml configuration
<?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> <!-- Archive daily files--> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- Limit a single file size --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- Limit a day's number of files --> <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> <!-- Archive daily files--> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- Limit a single file size --> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- Limit a day's number of files --> <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> <!-- Archive daily files--> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- Limit single file size--> <SizeBasedTriggeringPolicy size="2 MB" /> </Policies> <!-- Limit the number of files per day--> <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>Controller code:
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"; }}Running results
Logs will be stored in different files according to different levels. When the log file size exceeds 2M, multiple files will be compressed and stored. It is recommended to adjust the log file size of the production environment to 20-50MB.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.