Spring Boot – Using log4j logging

Spring boot uses an opinionated approach for a lot of things, with logging being one. It uses Logback by default. While Logback is useful, some of you may want to use a different log library. What do you have to do to use log4j as the logger?

It is actually very simple. All you have to do is

  1. Add the correct dependency in the pom.xml file
  2. Add the log4j properties file in the class path
  3. Add logging statements in your class

We are going to use the same project we looked at earlier for other Spring boot articles.


Add the following highlighted dependencies to the 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/xsd/maven-4.0.0.xsd">













Here the highlighted GAV values are the ones that disable the internal LogBack logging and uses log4j. This is shown in the exclusion section and also on the dependency section right after that.

Once this change is complete in the pom.xml file, add a log4j.properties file in src/main/resources folder. This folder is where we have the application.properties file defined as well.



Contents of the log4j.properties file is shown above. This is a very simple example and does not include all the other customization usually done with log4j.

The project structure should be as below.

spring boot art3 a

All that is left is to update the class and run the application

package com.atechref.spring;

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

 * Spring boot app
 * @author APeter
public class App {

    // define the logger
    private static Logger log = Logger.getLogger(App.class);

    public static void main( String[] args ) {
        log.info("Logger enabled: Entering main \n\n");
        SpringApplication app = new SpringApplication(App.class);
        log.info("Exiting main");

Now when we run the application we see the log output as highlighted below.

spring boot art3 b


spring boot art3 c

Now we have logging using log4j enabled with our Spring Boot application




Leave a Reply

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