When the background program is developed and launched, log information printing and log log recording are generally used. During development, log information printing can quickly locate the problem and help us develop quickly. If a bug or error occurs after the program is online, log records are needed to find the problem.
Spring Boot can integrate many different logging systems, among which the most commonly used Apache Log4j, and Log4j 2 is an upgraded version of Log4j, which has made many significant improvements compared to Log4j 1.x. So this blog will directly talk about how Spring Boot integrates and configures Log4j2.
1. Import Log4j2 package
If you are using Gradle, add the following dependencies in the build.gradle file. The Gradle method is used in the sample code.
dependencies { // log4j2 compile "org.apache.logging.log4j:log4j-api:2.8" compile "org.apache.logging.log4j:log4j-core:2.8" // Used to support Async compile in Logger 'com.lmax:disruptor:3.3.6'}If you are using Maven, add the following dependencies in the pom.xml file.
<dependencies> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.8</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.8</version> </dependency> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.3.6</version> </dependency></dependencies>
2. Add log4j2 configuration file
Create the log4j2.xml file in the root directory of the project's resources resource file and copy the following code into the file.
<?xml version="1.0" encoding="UTF-8"?><!-- The status after Configuration is used to set the information output inside log4j2 itself. It can be not set. When it is set to trace, you will see various detailed outputs inside log4j2. Can be set to OFF (off) or Error (only output error information) --><Configurationstatus="OFF"> <!-- Log file directory and compressed file directory configuration --> <Properties> <Propertyname="fileName">/home/kylin/log/knight/spring_log</Property> <Propertyname="fileGz">/home/kylin/log/knight/spring_log/7z</Property> </Properties> <Appenders> <!-- Configuration for output console logs --> <Consolename="console"target="SYSTEM_OUT"> <!--Console only outputs information at level and above (onMatch), and other direct rejections (onMismatch) --> <ThresholdFilterlevel="info"onMatch="ACCEPT"onMismatch="DENY"/> <!-- Output log format--> <PatternLayoutpattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> <!-- Print out all information. Each time the size exceeds size, the log of this size will be automatically stored in the folder created by year-month and compressed as an archive--> <RollingRandomAccessFilename="infoFile"fileName="${fileName}/web-info.log"immediateFlush="false" filePattern="${fileGz}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.web-info.gz"> <PatternLayoutpattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} [%t] %-5level %logger{36} %L %M - %msg%xEx%n"/> <Policies> <TimeBasedTriggeringPolicyinterval="6"modulate="true"/> <SizeBasedTriggeringPolicysize="50 MB"/> </Policies> <Filters> <!-- Record only info and warning level information --> <ThresholdFilterlevel="error"onMatch="DENY"onMismatch="NEUTRAL"/> <ThresholdFilterlevel="info"onMatch="ACCEPT"onMismatch="DENY"/> </Filters> <!-- Specify the maximum number of compressed packets per day, default 7, if it exceeds the previous one, it will overwrite --> <DefaultRolloverStrategymax="50"/> </RollingRandomAccessFile> <!-- Store all error information--> <RollingRandomAccessFilename="errorFile"fileName="${fileName}/web-error.log"immediateFlush="false" filePattern="${fileGz}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.web-error.gz"> <PatternLayoutpattern="%d{yyyyy-MM-dd 'at' HH:mm:ss z} [%t] %-5level %logger{36} %L %M - %msg%xEx%n"/> <Policies> <TimeBasedTriggeringPolicyinterval="6"modulate="true"/> <SizeBasedTriggeringPolicysize="50 MB"/> </Policies> <Filters> <!-- Record only error level information --> <ThresholdFilterlevel="error"onMatch="ACCEPT"onMismatch="DENY"/> </Filters> <!-- Specify the maximum number of compressed packets per day, default 7, if it exceeds the previous one, it will overwrite --> <DefaultRolloverStrategymax="50"/> </RollingRandomAccessFile> </Appenders> <!-- Specify the maximum number of compressed packets per day, the default is 7, and the previous one will be overwritten --> <DefaultRolloverStrategymax="50"/> </RollingRandomAccessFile> </Appenders> <!-- Global configuration, by default all Loggers inherit this configuration --> <Loggers> <!-- AsyncRoot - Asynchronous logging - requires support from LMAX Disruptor --> <AsyncRootlevel="info"additivity="false"> <AppenderRefref="console"/> <AppenderRefref="infoFile"/> <AppenderRefref="errorFile"/> </AsyncRoot> </Loggers></Configuration>3. Write Log4j2 auxiliary class
After making the above configuration, we can write an auxiliary class to make it more convenient for us to use Log4j2 to record logs.
Create an L.java class file in the utils package.
package com.spring.log4j2.utils;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;/** * Logger Logging auxiliary class* * Created by Kylin on 2017/5/11. */public classL{ private static final Logger LOGGER = LogManager.getLogger(); privateL(){ /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } publicstaticLoggergetLogger(){ return LOGGER; } publicstaticvoidt(String msg){ LOGGER.trace(msg); } publicstaticvoidd(String msg){ LOGGER.debug(msg); } publicstaticvoidi(String msg){ LOGGER.info(msg); } publicstaticvoidw(String msg){ LOGGER.warn(msg); } publicstaticvoide(String msg){ LOGGER.error(msg); }}After writing the auxiliary class, it is very simple to use, and it can be easily used through the following code.
@Controllerpublic classWebController{ @RequestMapping("/") publicStringindex(){ String msg = "Configuration and use of Log4j2 in Spring Boot series"; Lt(msg); Ld(msg); Li(msg); Lw(msg); Le(msg); return "index"; }}The auxiliary class here just writes some basic usage methods, you can customize them according to your needs and add more auxiliary methods. For methods not provided in the helper class, you can also use the L.getLogger() method to get the Logger instance to use.
4. Result verification
Level rating of logs: TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
Because the level in my log4j2 is set to the INFO level. Therefore, only three levels of INFO, WARN, and ERROR can be seen in the printing information (the information at the FATAL level is not printed, otherwise it can be seen).
The printing information is shown in the figure below:
At the same time, a Log file was generated in the computer system, as shown in the figure below:
By observing the path, you can find that this path is exactly the path set in Log4j2.xml:
<!-- Log file directory and compressed file directory configuration--><Properties> <Propertyname="fileName">/home/kylin/log/knight/spring_log</Property> <Propertyname="fileGz">/home/kylin/log/knight/spring_log/7z</Property></Properties>
5. More
Log4j2's Github address: https://github.com/apache/logging-log4j2
The sample code address of this tutorial: https://github.com/dkylin/SpringBoot-Sample/tree/master/SpringBoot-log4j2
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.