0

I am trying to use log4j2 in a Spring boot application with Gradle. I have 4 different profiles: it, dev, mac, was. Correspondingly, I have 4 different log4j2 config files: log4j2-it.xml, log4j2-dev.xml, log4j2-mac.xml, log4j2-was.xml. Based on the selected profile, I want to pick the correct log4j2 configuration file so that it is configured accordingly.

First off, to get log4j2 to even work, I excluded spring-boot-starter-logging and included instead spring-boot-starter-log4j2. Before doing this log4j2 did not work at all.

I’ve looked into this post, but I could not get the accepted answer to work. According to this post, setting the logging.config property won’t work. Furthermore, my project does not have a start script, so I cannot pass the argument with the -D flag.

I have been able to select one of the configuration files by adding a log4j2.component.properties file and specifying the config file to use there (see here), however I haven’t found a way to make this profile-dependent.

Also if I have a file named just log4j2.xml, this is discovered and loaded as expected.

After doing a lot of searching, I’ve seen a bunch of solutions for logback and given them a try to see if any would work with log4j2, but unsurprisingly none of these were successful.

Is there a way for me to accomplish this? For example, when running tests the it profile is selected and the log4j2-it.xml file should be used to configure logging. Perhaps there’s something I’ve missed, as I would expect that profile-specific log4j2 configuration should be possible, but thus far I have not found anything that works.

knueser
  • 357
  • 3
  • 14

1 Answers1

0

I ended up adding a @Component with a @PostConstruct method wherein I did

LoggerContext context = (LoggerContext)LogManager.getContext(false);
context.setConfigLocation(URI.create("path to file"));
context.reconfigure();

Thanks to alan7678's answer here.

knueser
  • 357
  • 3
  • 14