How to configure Apache Log4j2 with Spring Boot

Apache Log4j2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback’s architecture.The tutorial will introduce way to configure Log4j2 with Spring Boot

Related Posts:
Logging with SLF4J
Logging with SLF4J and Logback


I.Technology for Apache Log4j2 tutorial

– Java 8
– Maven 3.3.9
– Spring Boot: 1.4.0.RELEASE
– Editor: Spring Tool Suite – Version:3.8.0.RELEASE

II. Overview Spring Log4j2
1. Structure of Project

structure-springboot-log4j2

2. Step To Do

– Create Spring Boot project.
– Configure dependency for Log4j2
– Create a SimpleController.
– Configure log4j2.xml file
– Build & Run

III. Practice
1. Create Spring Boot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, Input all needed information:

create-spring-boot-log4j2

Press Next then press Finish, project will be created successfully.

2. Configure Spring Boot Log4j2 dependencies

– Exclude logback from default log dependency of Spring Boot

– Add Spring Web MVC dependency:

– Add Log4j2 dependency

3. Create a Simple Controller

We define a logger which is ready for showing messages with 4 mode: Debug, Info, Warn, Error

4. Configure Log4j2.xml

– Create a log4j2.xml file for configuration log4j2 (Spring will understand that the “log4j2.xml” file is a configuration for log4j2).

– Create 3 Loggers:

– With 3 Appenders:

– Full Details:

5. Build & Run

– Build Spring Boot project with goals:
clean install

– Run Spring Boot project with mode: Spring Boot App
Because levellog = INFO so DEBUG log is missed, Result is:

IV. Sourcecode

SpringBootLog4J2


Related Posts


2 thoughts on “How to configure Apache Log4j2 with Spring Boot”

Got Something To Say:

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

*