Spring Boot - log4j 2 configuration example

Posted on November 28, 2017

By default, if you are using the ‘Starter’ in your Spring Boot application, the Logback framework will be used for logging. 

In this post, you will learn how to configure the log4j 2 framework in Spring boot application.

Tool and technologies used for this example are -

  • Spring Boot 1.5.8.RELEASE
  • Log4j 2.7
  • Maven 3.5.2
  • Eclipse Neon.3 (4.6.3)

Let's see an example …

Project Structure

Review the following maven project structure.


Related - How to create a maven project in eclipse IDE.

Jar dependencies

As we know, by default the Logback is used for logging if you using Starter for dependences management. To use the log4j 2 in spring boot application, you need to exclude the Logback and then include log4j 2 Starter as follows.


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

Log4j 2 Configuration

Create log4j2.xml file under src/main/resources folder and write the following code in it.


<?xml version="1.0" encoding="UTF-8"?>
    <!-- Console Appender -->
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
    <!-- File Appender -->
    <File name="File" fileName="d:/app.log">
      <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />

    <!-- Log everything in custom package -->
    <Logger name="com.boraji.tutorial.springboot" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />

    <!-- Log everything in Spring Boot -->
    <Logger name="org.springframework.boot" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />

    <!-- Log everything in Spring Core -->
    <Logger name="org.springframework.core" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />

    <Root level="error">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />


Run application

Create a main class, annotated with @SpringBootApplication annotation, to test the log4j 2 configuration as follows.


package com.boraji.tutorial.springboot;

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

public class MainApp {
  private static Logger logger = LogManager.getLogger(MainApp.class);

  public static void main(String[] args) {
    logger.info("Starting Spring Boot application..");
    SpringApplication app = new SpringApplication(MainApp.class);

After executing the MainApp.java, your console output will look like as follows.


Download Sources