The more commonly used logging tool classes in Java are log4j, slf4j, commons-logging (JCL), Logback, Log4j2 (log4j upgrade), and JDK logging.
Spring Boot uses Logback by default, but in comparison, Log4j2 is better on performance.
Using Log4j2 in Spring Boot (version 1.5.10.RELEASE
) is very simple and adds the following dependencies:
<!--Exclude Spring Boot ' s Default Logging --<dependency> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-starter-logging</artifactId> </exclusion> </exclusions></dependency><!--Add log4j2 Dependency --<dependency> <groupId>Org.springframework.boot</groupId> <artifactId>Spring-boot-starter-log4j2</artifactId></dependency><!--Needed for Async Logging with log4j 2 --<dependency> <groupId>Com.lmax</groupId> <artifactId>Disruptor</artifactId> <version>3.3.6</version></dependency><!--Use jsonlayout must rely on Jackson --<dependency> <groupId>Com.fasterxml.jackson.core</groupId> <artifactId>Jackson-core</artifactId> <version>2.7.4</version></dependency><dependency> <groupId>Com.fasterxml.jackson.core</groupId> <artifactId>Jackson-databind</artifactId> <version>2.7.4</version></dependency>
Then src/main/resources
add the log4j2.xml
configuration file in (Spring Boot will also recognize log4j2.json
and log4j2.yaml
):
<?xmlVersion= "1.0" encoding= "UTF-8"?><!--status represents the log information print level for LOG4J2 itself, and the following levels, not a concept--<!--TRACE < DEBUG < INFO < WARN < ERROR < FATAL < off--><configurationstatus="OFF"monitorinterval="a"> <Properties> <propertyname="Log_pattern">%d{yyyy-mm-dd HH:mm:ss. SSS}%5p ${hostname}-& #45;& #45;[%15.15t]%-40.40c{1.}:%m%n%ex</Property> <propertyname="Log_file_path">/var/log/spring-boot-log4j2</Property> </Properties> <Appenders> <consolename="Consoleappender"target="System_out"follow="true"> <patternlayoutpattern="${log_pattern}"/> </Console> <!--rolling File Appender -- <rollingfilename="Fileappender"filename="${log_file_path}/spring-boot-log4j2-demo.log"filepattern="${log_file_path}/spring-boot-log4j2-demo-%d{yyyy-mm-dd}-%i.log"> <PatternLayout> <Pattern>${log_pattern}</Pattern> </PatternLayout> <!--<jsonlayout complete= "false" compact= "true" ><keyvaluepair key= "timestamp" value= "$${date:yyyy-mm-dd ' T ' HH:mm:ss. SSSZ} "/></JsonLayout>--> <Filters> <!--only error level log information is logged, and other information printed by the program is not logged- <!--This level of logging is the log information printed in the filter log file, which is different from the levels of root. <thresholdfilterlevel="ERROR"onmatch="ACCEPT"onmismatch="DENY" /> </Filters> <Policies> <sizebasedtriggeringpolicysize="10MB" /> <!--Create a log file every day -- <timebasedtriggeringpolicyinterval="1" /> </Policies> <defaultrolloverstrategymax="Ten"/> </RollingFile> </Appenders> <Loggers> <!--used to specify the form of the log individually, such as specifying a different log level for the class under the specified package. - <!--<logger name= "com.easyjijin.demo.springbootlog4j2" level= "Debug" additivity= "false" ><appenderref ref= "Consoleappender"/><appenderref ref= "Fileappender"/></Logger>--> <!--asyncroot-Asynchronous logging-requires Lmaxdisruptor support -- <!--<asyncrootlevel= "info" additivity= "false" ><appenderref ref= "Console"/><appenderref ref= "Fileappender"/></AsyncRoot> <!--All < Trace < Debug < Info < Warn < Error < Fatal < OFF. <!--The program prints logs above or equal to the level you set, the higher the log level is, the fewer logs will be printed. - <!--This level of logging, which is the log information that is output from the filtered project, is different from the levels of Thresholdfilter. <rootlevel="ERROR"> <appenderrefref="Consoleappender" /> <appenderrefref="Fileappender"/> </Root> </Loggers></Configuration>
Here are a few log levels to note:
Configuration status="OFF"
: This status
configuration is the log level of the LOG4J2 component itself, which refers to the log level configuration that is printed out if the log4j2 itself is faulted.
Root level="ERROR"
: This level
configuration is the log level of the program input, corresponding log.error("this is a error")
to the program will print the log above or equal to the level set.
ThresholdFilter level="ERROR"
: This level
configuration is output to the log file (or other) log level, that is, the log file only output ERROR
level of the log, the other irrelevant information is not output.
To print log information using LOG4J2 in your program:
@SpringBootApplication Public classLog4j2demoapplicationImplementsApplicationrunner {Private Static FinalLogger Logger = Logmanager.GetLogger(Log4j2demoapplication.class); Public Static void Main(string[] args) {springapplication.Run(Log4j2demoapplication.class, args); }@Override Public void Run(Applicationarguments applicationarguments)throwsException {logger.Debug("Debugging Log"); Logger.Info("Info Log"); Logger.warn("Hey, this is a warning!"); Logger.Error("oops! We have an Error. OK "); Logger.Fatal("damn! Fatal error. Please fix me. "); }}
Or Lombok
, you can use log4j2 more conveniently, you need to add dependencies:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId></dependency>
Using code:
import lombok.extern.log4j.Log4j2;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@Log4j2@RestControllerpublicclass HelloController { @RequestMapping("/home") publichome() { log.error("Hi ! We have an Error. Hello World"); return"Hello World ----spring-boot-log4j2"; }}
Note: If the idea error (cannot be found log
), you can add the Lombok plugin to the idea settings.
Resources:
- Research on the status of log tools
- Performance measurement of Logback log4j log4j2
- How to use log4j 2 with Spring Boot ( recommended )
- Spring Boot + log4j2 Log Framework configuration (Maven)
- Have a chat log4j2 configuration file log4j2.xml ( configuration details )
- Spring-boot Log LOG4J2 Configuration
Spring Boot uses log4j2