Integrate and use the Log4j2 logging framework in Spring Boot

Insert image description here

In this tutorial, we will learn how to integrate the Log4j2 logging framework with Spring Boot.

Introduction to Log4j2

Spring Boot uses Logback as the logging framework by default. Next we will learn how to integrate and configure Log4j2 in Spring Boot. Before configuring, what we need to know is that Log4j2 is an upgraded version of Log4j. It has made many improvements based on Log4j:

  • 1. Asynchronous log;
  • 2. Support Java8 lambda style lazy loading log;
  • 3. Filter;
  • 4. Plug-in;
  • 5. Concurrency improvements;
  • 6. Support: SLF4J, Commons Logging, Log4j-1.x and java.util.logging;
  • 7. Configure hot loading;
  • 8. Customize log level;

Seeing the above new features, we definitely want to use Log4j2 in our Spring Boot application

Add Maven dependencies

Spring Boot uses logback by default. If we want to use Log4j2, we need to first exclude the default logging framework and then add the log4j2 dependency. The following is the pom.xml file:

<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>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId> 
</dependency>

Add Gradle dependency (optional)

If you are building the project through Gradle, see below:

dependencies {
    
    
    compile 'org.springframework.boot:spring-boot-starter-log4j2'
} 
configurations {
    
    
    all {
    
    
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
}

Add Log4j2 configuration file

Spring Boot supports the following 4 formats of configuration files:

  • 1.xml (default)
  • 2.json
  • 3.yaml
  • 4.properties file

Spring Boot if found in the classpath: directory log4j2.xml or log4j2.json or log4j2.properties or any one of the configuration files log4j2.yaml will be automatically loaded and used.

Next, let’s take a look at the log4j2.xml format. How to configure it?

Create configuration file in the /src/main/resource directory:log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="PID">????</Property>
        <Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n%xwEx</Property>
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

Create configuration files through Properties files (optional)

If you don’t like the xml method, you can also choose to create :< in the /src/main/resources directory /span>log4j2.properties

status = error
name = Log4j2Sample
appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} - %msg%n
rootLogger.level = warn
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Log4j2 in practice

After everything is ready, we create a test interface in the Application startup class and print the log in the interface:

package site.exception.springbootlog4j2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringBootLog4j2Application {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(SpringBootLog4j2Application.class, args);
    }
    private static final Logger LOG = LogManager.getLogger(SpringBootLog4j2Application.class);
    @GetMapping("/test")
    public String test() {
    
    
        LOG.debug("debug 级别日志 ...");
        LOG.info("info 级别日志 ...");
        LOG.warn("warn 级别日志 ...");
        LOG.error("error 级别日志 ...");
        LOG.fatal("fatal 级别日志 ...");
        return "Hello Log4j2 !";
    }
}

Start the project and look at the console output:

2023-10-06 22:15:59.815 INFO 11936 --- [nio-8080-exec-1] s.e.s.SpringBootLog4j2Application : info 级别日志 ...
2023-10-06 22:15:59.815 WARN 11936 --- [nio-8080-exec-1] s.e.s.SpringBootLog4j2Application : warn 级别日志 ...
2023-10-06 22:15:59.815 ERROR 11936 --- [nio-8080-exec-1] s.e.s.SpringBootLog4j2Application : error 级别日志 ...
2023-10-06 22:15:59.815 FATAL 11936 --- [nio-8080-exec-1] s.e.s.SpringBootLog4j2Application : fatal 级别日志 ...

at last

Everyone is welcome to follow me [Xiaobai Technology Circle] and replyB01 or b01, I present Java related books and interview questions with both hands!

Guess you like

Origin blog.csdn.net/lcmaijia/article/details/134254628