Spring Top

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

>> LEARN SPRING

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 application.properties file and tell it where to find the logging config file:

logging.config=/path/to/log4j2.xml

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

logging.config=/path/to/log4j2-dev.xml

If we have other profiles – for example, “prod” – we only need to create a similarly named properties file – application-prod.properties 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:

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    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.

Spring bottom

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

>> THE COURSE
Generic footer banner
Comments are closed on this article!