Log4j2 with Spring Boot

In this article of Spring Boot, we will talk about using Log4j2 with Spring Boot application. Logging is one of the important features of any enterprise application and it comes with a powerful and flexible logging feature.

 

Introduction

Spring Boot has no mandatory logging dependency, except for the Commons Logging API. By default, it will add Logback as your default logging API. In this post we will look at how to integrate and configure Log4j2 in Spring Boot applications. Log4j2 gives several improvements to its predecessor which includes:

  1. Async Loggers.
  2. Java 8-style lambda support for lazy logging.
  3. Filtering.
  4. Plugin Architecture.
  5. Concurrency improvements.
  6. Supported APIs: SLF4J, Commons Logging, Log4j-1.x and java.util.logging.
  7. Automatically reload its configuration.
  8. Custom log levels.

With so many features, it’s a natural intention to use Log4j 2 with Spring Boot application.

 

1. Maven Dependency

To use Log4j 2 with your Spring Boot application, we need to exclude Logback and then include log4j 2 instead. This is how our pom.xml look like after changes:

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

 

1.1 Gradle Dependency

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

Above configuration will add Log4j2 capabilities to your Spring Boot application.

 

2. Log4J 2 Configuration

Spring Boot provides following 4 options to configure Log4J2 for your application:

  1. XML based configuration (default configuration)
  2. JSON
  3. YAML
  4. Properties file

It will automatically configure Log4J 2 if it find log4j2.xml or log4j2.json or log4j2.properties or log4j2.yaml in the classpath.

[pullquote align=”normal”]To configure Log4j 2 to use an alternative configuration file format, add the dependencies to the classpath [/pullquote]

We will focus on the log4j2.xml file. Create a file with name log4j2.xml inside the src/main/resources directory. This is how our log4j2.xml file look like:

<?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>
        <Logger name="com.javadevjournal" level="debug"  additivity="false">
            <AppenderRef ref="Console" />
        </Logger>
       <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

This is a simple configuration to enable Log4J2 logging feature for your Spring Boot application.

 

2.1 Log4J 2 Configuration Using Property File

If you don’t like to use the log4j2.xml file, you can also add log4j2.properties in src/main/resources folder. This is how our properties file look like:

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

For more detail, read Spring Boot logging with application.properties

3. Log4J 2 in Action

Let’s create a simple controller to see our  Log4J 2 in action. If you are working on a spring boot standalone application, you have the option to use the CommandLineRunner.

@RestController
public class Log4J2Controller {

    private static final Logger LOG = LogManager.getLogger(Log4J2Controller.class);

    @GetMapping(value = "/greeting")
    public String greeting() {

        LOG.debug("Debugging log in our greeting method");
        LOG.info("Info log in our greeting method");
        LOG.warn("Warning log in our greeting method");
        LOG.error("Error in our greeting method");
        LOG.fatal("Damn! Fatal error. Please fix me.");
        return "Hello!!!";
    }
}

On running our example, we may see an identical output in the console:

2019-01-14 22:20:17.921 DEBUG 40753 --- [nio-8080-exec-2] c.j.Log4J2Controller     : Debugging log in our greeting method
2019-01-14 22:20:17.921  INFO 40753 --- [nio-8080-exec-2] c.j. Log4J2Controller     : Info log in our greeting method
2019-01-14 22:20:17.921  WARN 40753 --- [nio-8080-exec-2] c.j.Log4J2Controller     : Warning log in our greeting method
2019-01-14 22:20:17.921 ERROR 40753 --- [nio-8080-exec-2] c.j.Log4J2Controller     : Error in our greeting method

Above logging pattern is based on our log4j2.xml configuration. In the section we will have a closer look at some common Log4J2 configuration for our Spring Boot application:

 

Summary

In this post, we explain how to use Log4j2 with Spring Boot application. We discuss steps to configure Log4j2 and how to set the logging configurations using log4j2.xml or log4j2.json or log4j2.properties or log4j2.yaml in the classpath.Let me know if you are experiencing any issue while setting up Log4j2 with Spring Boot application. Source code for this post is available on our GitHub repository.

1 thought on “Log4j2 with Spring Boot”

  1. I dont not want to build my log4j programitically. I am trying to get log location file path from boostrap.properties which is kept at server level. Do anyone know how do we use that property in log4j.xml ?

Comments are closed.