Spring Boot Log4j2.xml Example

Spring boot log4j2.xml configuration example of configuring log4j2 with spring boot2 project and adding logging support to the application.

spring boot logo

Spring boot’s default logging uses Logback which is included as a transitive dependency. Spring Boot supports Log4j2 for logging configuration if it is on the classpath and Logback is excluded.

To configure Log4j2 with Spring Boot2, follow these two simple steps:

1. Log4j2 Maven Dependency

In fact, it is two steps change. First, remove spring’s default spring-boot-starter-logging starter dependency which excludes Logback from the classpath. Then add the spring-boot-starter-log4j2 starter dependency.

 <dependencies>
  <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>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
  </dependency>
</dependencies>

2. Add log4j2.xml File in /resources Folder

Spring will automatically configure log4j2 once it finds its jar files in the classpath. Now we have to add log4j2.xml or (log4j2.properties) in src/main/resources folder. That’s all.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>
        <Property name="APP_LOG_ROOT">c:/temp</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="${LOG_PATTERN}" />
        </Console>
        <RollingFile name="appLog"
                fileName="${APP_LOG_ROOT}/SpringBoot2App/application.log"
                filePattern="${APP_LOG_ROOT}/SpringBoot2App/application-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${LOG_PATTERN}" />
            <Policies>
                <SizeBasedTriggeringPolicy size="19500KB" />
            </Policies>
            <DefaultRolloverStrategy max="1" />
        </RollingFile>
    </Appenders>

    <Loggers>
        <Logger name="com.howtodoinjava.app" additivity="false">
            <AppenderRef ref="appLog" />
            <AppenderRef ref="Console" />
        </Logger>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="appLog" />
        </Root>
    </Loggers>
</Configuration>

3. Demo

Now add a few log statements in the application and see the logs in configured appenders e.g. I configured console and file.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
 
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
 
  private static final Logger LOGGER = LogManager.getLogger(Application.class);
 
  public static void main(String[] args)
    {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
         
        LOGGER.info("Info level log message");
        LOGGER.debug("Debug level log message");
        LOGGER.error("Error level log message");
    }
}

Check the output in the console and the log file.

2018-06-01T13:55:42.506+0530 INFO Info level log message
2018-06-01T13:55:42.506+0530 DEBUG Debug level log message
2018-06-01T13:55:42.506+0530 ERROR Error level log message

Let me know if you face any problems in this spring boot log4j2 example.

Happy Learning !!

Leave a Comment

  1. Hi, I’m using exactly the same dependency you got right now. If I want to customize the config filename to log4j2-spring.xml with setting logging.config=classpath: log4j2-spring.xml in application.properties, it doesn’t recognize the config file at all. I don’t know what’s wrong.

    Reply
    • 1. Ensure that there are no spaces before or after the colon (:) in the file path.
      2. Enable debug logging to get more insights into what’s happening during the application startup with logging.level.org.springframework=DEBUG

      Reply
      • I added logging.level.org.springframework=DEBUG, and remove ths space. Nothing was reported wrong while build.

        $ ./mvnw spring-boot:run
        Warning: JAVA_HOME environment variable is not set.
        [INFO] Scanning for projects…
        [INFO] 
        [INFO] ———————-< com.wago:print-converter >———————-
        [INFO] Building print-converter 0.0.1-SNAPSHOT
        [INFO]  from pom.xml
        [INFO] ——————————–[ jar ]———————————
        [INFO] 
        [INFO] >>> spring-boot:3.2.3:run (default-cli) > test-compile @ print-converter >>>
        [INFO] 
        [INFO] — resources:3.3.1:resources (default-resources) @ print-converter —
        [INFO] Copying 1 resource from src\main\resources to target\classes
        [INFO] Copying 1 resource from src\main\resources to target\classes
        [INFO]
        [INFO] — compiler:3.11.0:compile (default-compile) @ print-converter —
        [INFO] Nothing to compile – all classes are up to date
        [INFO]
        [INFO] — resources:3.3.1:testResources (default-testResources) @ print-converter —
        [INFO] skip non existing resourceDirectory C:\Projects\PrintConverter\src\test\resources
        [INFO]
        [INFO] — compiler:3.11.0:testCompile (default-testCompile) @ print-converter —
        [INFO] Nothing to compile – all classes are up to date
        [INFO]
        [INFO] <<< spring-boot:3.2.3:run (default-cli) < test-compile @ print-converter <<<
        [INFO]
        [INFO]
        [INFO] — spring-boot:3.2.3:run (default-cli) @ print-converter —
        [INFO] Attaching agents: []
        15:04:48.853 [main] ERROR com.wago.printconverter.PrintConverterApplication – Error loggggg message
        15:04:48.856 [main] ERROR com.wago.printconverter.PrintConverterApplication – Error log message
        [INFO] ————————————————————————
        [INFO] BUILD SUCCESS
        [INFO] ————————————————————————
        [INFO] Total time: 1.960 s
        [INFO] Finished at: 2024-03-14T15:04:48+08:00
        [INFO] ————————————————————————

        Here is my main.
        private final static Logger logger = LoggerFactory.getLogger(PrintConverterApplication.class);

            public static void main(String[] args) {

                // logger.info(System.getProperty(“java.class.path”));
                // SpringApplication.run(PrintConverterApplication.class, args);
                logger.error(“Error loggggg message”);
                logger.info(“PrintConverterApplication ended.”);
                logger.debug(“Debug log message”);
                logger.info(“Info log message”);
                logger.error(“Error log message”);
            }

        Only 2 log.error work without formatting.

        Reply
  2. Hi, I am getting the below exception in spring Boot :
    SLF4J: Class path contains multiple SLF4J bindings.
    SLF4J: Found binding in [jar:file:/Users/sachin.raghav/ .m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.17.0/log4j-slf4j-impl-2.17.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: Found binding in [jar:file:/Users/sachin.raghav/.m2/repository/ch/qos/logback/logback-classic /1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: See http://www.slf4j.org/codes.html #multiple_bindings for an explanation.
    SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
    Exception in thread “main” java.lang.ExceptionInInitializerError
    Caused by: org.apache.logging.log4j.LoggingException: log4j-slf4j-impl cannot be present with log4j-to-slf4j
    at org.apache.logging.slf4j.Log4jLoggerFactory .validateContext(Log4jLoggerFactory.java:60)

    please suggest a fix for the given issue.

    Reply
  3. I am getting this problem and in the console and Info and error log is showing on console but debug line is not printing on console

    SLF4J: Class path contains multiple SLF4J bindings.
    SLF4J: Found binding in [jar:file:/C:/Users/1707393/.m2/repository/ ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: Found binding in [jar:file:/C:/Users/1707393/.m2/repository/ org/apache/logging/log4j/log4j-slf4j-impl/2.12.1/log4j-slf4j-impl-2.12.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
    SLF4J: See https://www.slf4j.org/codes.html#multiple_bindings for an explanation.
    SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
    Reply
    • In Springboot the default logging level is INFO which means info and higher logging levels be printed, like ERROR, WARN, FATAL etc but lower levels like DEBUG and TRACE wont be printed. Change the logging level to see DEBUG logs

      Reply
  4. Hi Getting below error while starting boot app

    ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console…

    snippet:

    org.springframework.boot
    spring-boot-starter-web

    org.springframework.boot
    spring-boot-starter-logging

    org.springframework.boot
    spring-boot-starter-log4j2

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.