Spring boot log4j2 properties example

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

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

1. Add Log4j2 Maven Dependency

In fact, it is two steps change. First remove spring’s default logging dependency (spring-boot-starter-logging) and then add log4j2 dependency (spring-boot-starter-log4j2).

Spring will automatically configure log4j2 once it finds it’s jar files in classpath.




2. Add log4j2 properties file in resources folder

Now we have to add log4j2.properties or (log4j2.xml) in src/main/resources folder. That’s all.

status = error
name = PropertiesConfig

filters = threshold

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Read More: Log4j2 properties file example

3. Spring boot log4j2 properties logging example

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

package com.howtodoinjava.app;

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;

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.

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 have any question on spring boot log4j2 properties congiguration.

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

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.

Our Blogs

REST API Tutorial