avatar
setup Log4j in a Spring Boot application Spring Boot

• Assuming that you have an understanding of the folder structure for a Spring Boot project, the following is an overview of the code structure folders:

myspringboot/
  + src/
  | + main/
  | | + java/
  | | | + com/
  | | | | + flagtick/
  | | | |   + core/
  | | | |     + config/
  | | | |     + controller/
  | | | |     + model/
  | | | |     + repository/
  | | | |     + service/
  | | | |     - MyProjectApplication.java
  | | + resources/
  | |   - application.properties
  | |   - log4j2.xml
  | - test/
  |   + java/
  |   | + com/
  |   | | + flagtick/
  |   | |   + core/
  |   | |     + controller/
  |   | |     + model/
  |   | |     + repository/
  |   | |     + service/
  |   | |     - MyProjectApplicationTests.java
  - pom.xml

• Carry out of inserting the log4j dependency to your Spring Boot project's pom.xml file:

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.17.1</version>
</dependency>

The version 2.17.1 may be appropriate for your application needs and compatible with other dependencies we are using. If you need other version and let change.

Note: In the other hand, `spring-boot-starter-log4j2` is a Spring Boot starter that includes Log4j as the default logging implementation. Hence, you don't need to manually configure it yourself.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

• Create new configuration file named `log4j2.xml` or `log4j2.yml' in the `src/main/resources` directory. Here is an example log4j2.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    </Console>
  </Appenders>
  <Loggers>
    <Root level="info">
      <AppenderRef ref="Console" />
    </Root>
  </Loggers>
</Configuration>

• Come up to `MyProjectApplication.java` file and create LogManager instance so that we can take advantage of LogManager.getContext() to retrieve the current LoggerContext.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyProjectApplication {

  private static final Logger logger = LogManager.getLogger(MyProjectApplication.class);

  public static void main(String[] args) {
    SpringApplication.run(MyProjectApplication.class, args);
    // Example usage
    logger.info("Application started");
  }
}
24
getting started Spring Boot using Maven get spring boot to automatically create database schema
You need to login to do this manipulation!