Course – LS (cat=Spring)

Get started with Spring and Spring Boot, through the reference Learn Spring course:


1. Overview

In our previous tutorials, Spring Profiles and Logging in Spring Boot, we showed how to activate different profiles and use Log4j2 in Spring.

In this short tutorial, we’ll learn how to use different Log4j2 configurations per Spring profile.

2. Use Different Properties Files

For example, suppose we have two files, log4j2.xml and log4j2-dev.xml, one for the default profile and the other for the “dev” profile.

Let’s create our file and tell it where to find the logging config file:


Next, let’s create a new properties file for our “dev” profile named and add a similar line:


If we have other profiles – for example, “prod” – we only need to create a similarly named properties file – for our “prod” profile. Profile-specific properties always override the default ones.

3. Programmatic Configuration

We can programmatically choose which Log4j2 configuration file to use by changing our Spring Boot Application class:

public class Application implements CommandLineRunner {

    private Environment env;

    public static void main(String[] args) {, args);

    public void run(String... param) {
        if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
            Configurator.initialize(null, "/path/to/log4j2-dev.xml");
        } else {
            Configurator.initialize(null, "/path/to/log4j2.xml");

Configurator is a class of the Log4j2 library. It provides several ways to construct a LoggerContext using the location of the configuration file and various optional parameters.

This solution has one drawback: The application boot process won’t be logged using Log4j2.

4. Conclusion

In summary, we’ve seen two approaches to using different Log4j2 configurations per Spring profile. First, we saw that we could provide a different properties file for each profile. Then, we saw an approach for configuring Log4j2 programmatically at application startup based on the active profile.

Course – LS (cat=Spring)

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!