How to use log4j2 in Spring boot application

Log4j2 is one of the next generation Logging framework having some significant features which improve the performance of the application.

How to use log4j2 in spring boot

When we say it improves the performance, I really mean it, There are some important features which come in this next generation logging framework of Apache If you want to learn ( check here)


In this article, we will learn how to implement or add log4j2 in Spring boot application.

Also read: Top 5 Online Courses for Spring boot developer

We will first see the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>in.learnspringboot</groupId>
  <artifactId>Log4j2Demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Log4j2Demo</name>
  <description>Log4j2 Implementation</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <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-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--  below are the dependency need to add for log4j2 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>3.4.0</version>
    </dependency>
    <!-- end -->
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>


</project>

Things to be remember

We need to exclude the by default logging added in the spring boot readymade project.

<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>

Now You need to add the below log4j2.xml file in resource folder

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">
            %d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${hostName} --- [%15.15t] %-40.40c{1.} : %m%n%ex
        </Property>
    </Properties>

    <Appenders>
        <Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}"/>
        </Console>

        <!-- Rolling File Appender -->
        <RollingFile name="FileAppender" fileName="logs/app.log"
                     filePattern="logs/app-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout>
                <Pattern>${LOG_PATTERN}</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" />
                <SizeBasedTriggeringPolicy size="10MB" />
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>

    </Appenders>

    <Loggers>
        <AsyncLogger name="in.learnspringboot" level="debug"
                     additivity="false">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="FileAppender" />
        </AsyncLogger>

        <Root level="info">
            <AppenderRef ref="ConsoleAppender" />
            <AppenderRef ref="FileAppender" />
        </Root>
    </Loggers>
</Configuration>

Now when you added this file , Spring boot automatically read the configuration of the xml and will understand what need to do.

How to use the log4j2 in code

Here , we are adding the below line in below snippet.

private static org.apache.logging.log4j.Logger logger = LogManager.getLogger();

package in.learnspringboot;

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

@SpringBootApplication
public class Log4j2DemoApplication implements CommandLineRunner {
  
  private static org.apache.logging.log4j.Logger logger = LogManager.getLogger();

  public static void main(String[] args) {
    SpringApplication.run(Log4j2DemoApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
//		this method is to show the logger use
    System.out.println("This will see on console");
    logger.debug("this will save in log file");
    
    
    
  }
}

After running the code you will see that the logs will be saved in the logs/app.log file

If you have any problem you can see the code from github

 

You may also like...

2 Responses

  1. default says:

    Nіce post. I was chеckіng continuously thiѕ blog and I
    am impressed! Extremely սsеful info specifically
    the last part 🙂 I care for such infօrmation a lоt.

    I was looking for this particular information for a long tіme.
    Тhank you and best of luck.

  1. August 29, 2018

    […] Read Also: Log4j2 in Spring boot Application […]

Leave a Reply

Your email address will not be published. Required fields are marked *