Spring Boot and log4j2 intergation Example

In our previous article we have seen how to create Spring Boot RESTful Web services, In this article we will see, How to enable Logging in Spring Boot using log4j2.

We will disable the default spring boot logging to add log4j2 support, let's first Create a spring maven project and import it in eclipse.

Dependencies (pom.xml)

In order to disable default spring boot logging we need to exclude spring-boot-starter-logging and to enable log4j2 logging a spring-boot-starter-log4j2 has to be added in pom.xml as shown below:
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tb.java</groupId>
	<artifactId>SpringBoot2Maven</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SpringBoot2Maven</name>
	<url>http://maven.apache.org</url>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.3.RELEASE</version>
	</parent>

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

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

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

	<repositories>
		<repository>
			<id>repository.spring.release</id>
			<name>Spring GA Repository</name>
			<url>http://repo.spring.io/release</url>
		</repository>
	</repositories>
</project>

Create log4j2.xml configuration

If no log4j2.xml configuration found in classpath, a default configuration will be applied; to add a custom log4j2 configuration add a log4j2.xml file in classpath as shown below:

/src/main/resources/log4j2.xml
<?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>
    </Appenders>
    <Loggers>
        <Logger name="com.tb.java" level="debug" additivity="false">
            <AppenderRef ref="ConsoleAppender" />
        </Logger>

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

Create application.properties

In order to tell spring boot to consider log4j2.xml file for logging behaviour we need to add an entry with full path in application.properties, as shown below:

/src/main/resources/application.properties
logging.config=src/main/resources/log4j2.xml

Create Spring boot application launch class

Here, @SpringBootApplication does all the magic, a class having main() and annotated with @SpringBootApplication is called Spring boot application launch class.

/src/main/java/com/tb/java/App.java
package com.tb.java;

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

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class App {
	private static final Logger LOGGER = LogManager.getLogger(App.class);

	public static void main(String[] args) {
		ApplicationContext ctx = SpringApplication.run(App.class, args);
		LOGGER.debug("A DEBUG Message");
		LOGGER.info("An INFO Message");
		LOGGER.warn("A WARN Message");
		LOGGER.error("An ERROR Message");
	}
}


Run and launch application

Now we are all done with creating a Spring Boot project with log4j2 logging enabled, lets run the application from application launch class to see log messages:

If everything goes right, you will see something like this in Eclipse console, along with log messages printed in the end:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-03-01 14:52:26.566  INFO techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : Starting App on techie-ThinkPad-13-2nd-Gen with PID 17028 (/home/techie/git/SpringBootLg4j/target/classes started by techie in /home/techie/git/SpringBootLg4j)
2019-03-01 14:52:26.571 DEBUG techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : Running with Spring Boot v2.1.3.RELEASE, Spring v5.1.5.RELEASE
2019-03-01 14:52:26.572  INFO techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : No active profile set, falling back to default profiles: default
2019-03-01 14:52:26.992  INFO techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : Started App in 0.656 seconds (JVM running for 1.29)



2019-03-01 14:52:26.993 DEBUG techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : A DEBUG Message
2019-03-01 14:52:26.994  INFO techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : An INFO Message
2019-03-01 14:52:26.994  WARN techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : A WARN Message
2019-03-01 14:52:26.994 ERROR techie-ThinkPad-13-2nd-Gen --- [           main] c.t.j.App                                : An ERROR Message

Here We are done with creating a Spring Boot 2 project with log4j2 logging enabled, in upcoming articles we will see more about Spring Boot.

Download "Spring Boot 2 log4j2 project" source code from: GitHub.

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.