This tutorial guides you how to use Log4j2 – a popular Java logging framework – in a Spring Boot project.

 

1. Why Log4j2?

Log4j2 is a successor to Log4j 1.x. Log4j2 provides significant improvements over Log4j 1.x and it also fixes some issues in Logback – also a successor to Log4j 1.x. Log4j2 uses the next-generation asynchronous loggers so it’s faster and better than Log4j 1.x and Logback.

For details about Log4j2, visit its homepage here.

 

2. Configure Maven Dependencies for using Log4j2 in Spring Boot

Spring Boot uses Logback as the default logging framework implementation, so to use Log4j2 you need to do some extra configuration in the Maven project file.

First, you need to exclude spring-boot-starter-logging dependency:

<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>
Then declare a dependency for using Log4j2 as follows:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
Then you will see Spring Boot removes the jar files of Logback and adds jar files: log4j-core, log4j-slf4j (for bridge between Log4j and SLF4J), log4j-jul (for bridge between Log4j and Java Util Logging), and jul-to-slf4j (for bridge between Java Util Logging and SLF4J).



That means if the project is using SLF4J API, then you don’t have to change the existing logging code. And you see Java Util Logging because it is used for internal APIs of Spring Boot.

 

3. Configure Logging to Console (Console Appender)

Next, you need to create log4j2.xml or log4j2-spring.xml file under the src/main/resources directory in order to use Log4j2 for your Spring Boot project.

Below is the XML code for the simplest Log4j2 configuration: output log messages to the console.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d %t %level %c %msg %n" />
		</Console>
	</Appenders>

	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" />
		</Root>
	</Loggers>
</Configuration>
Let me explain the pattern layout for each line of log written to the console: %d for date and time, %t for thread name, %level for log level, %c for logger name (usually package name and class name), %msg for log message, and %n for a line separator.

You can use the following pattern for more readable log messages:

%d{yyyy-MMM-dd HH:mm:ss} [%t] %-5level %-50c{1.} - %msg%n
This pattern will indent the log level and logger name, also abbreviate logger names if too long.

 

4. Write Log Messages

It’s recommended to use SLF4J API so the logging code doesn’t depend on any particular logging framework. Declare a logger like this:

private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
with the following imports:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
And then you can write log messages with different log levels like this:

LOGGER.trace("for tracing purpose");
LOGGER.debug("for debugging purpose");
LOGGER.info("for informational purpose");
LOGGER.warn("for warning purpose");
LOGGER.error("for logging errors");
 

5. Configure Logging to File (File Appender)

Next, let’s configure Log4j2 to write logs to a file like this:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout
				pattern="%d{yyyy-MMM-dd HH:mm:ss} [%t] %-5level %-50c{1.} - %msg%n" />
		</Console>

		<File name="File" fileName="MyApp.log">
			<PatternLayout
				pattern="%d{yyyy-MMM-dd HH:mm:ss} [%t] %-5level %-50c{1.} - %msg%n" />
		</File>
	</Appenders>

	<Loggers>
		<Root level="info">
			<AppenderRef ref="Console" />
			<AppenderRef ref="File" />
		</Root>
	</Loggers>
</Configuration>
As you can see, we create a new appender for logging to a file named MyApp.log, which will be created in the same directory of the application.

 

Conclusion

That’s my guide to use Log4j2 in Spring Boot. I hope you’ve found it helpful, and you can also watch the video version of this tutorial below:

 

Other Spring Boot Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#3ramu2022-06-22 07:18
good work.......nice
Quote
#2khoa2021-10-22 05:19
Hi, thanks for helpful tutorial.

The file was not generated for me, still looking for the solution.
Quote
#1Zoya Khan2021-06-13 01:12
Hey this was really helpful. However i noticed 1 issue here. We i embedded this in my project having java 11, i found excluding with spring-boot-starter could not run the application. It resulted in ClassCastException: org.apache.logging.log4j.simple.SimpleLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext. So i excluded in spring-boot-starter-web artifact .
Quote