Load Log4j2 configuration file programmatically
For the newest version of log4j, here is what should work for loading an external log4j2.xml
:
String log4jConfigFile = System.getProperty("user.dir") + File.separator + "log4j2.xml";
ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4jConfigFile));
Configurator.initialize(null, source);
If you have a single main entry point, this code snippet might save you some trouble. The set property call must fire before any loggers are created. This approach works with files on the classpath.
public class TestProcess {
static {
System.setProperty("log4j.configurationFile", "log4j-alternate.xml");
}
private static final Logger log = LoggerFactory.getLogger(TestProcess.class);
}