I want to load a log4j2 XML configuration programmatically.
My config file is ok and the following two approaches work. One, rename it to log4j2.xml and put it in the classpath (but I have multiple so this was for experiment). Two, do this (which works, but I'm maintaining some older code and would rather try and keep their mechanisms intact)
static {
File _l4 = new File (DATA_DIR + File.separator + LOG_CONFIG_FILENAME);
System.setProperty("log4j2.configurationFile", _l4.toURI().toString());
}
From what I've found on here, this should work.
FileInputStream fileInputStream = new FileInputStream(pConfigFilename);
ConfigurationSource configurationSource = new ConfigurationSource(fileInputStream);
Configurator.initialize(null, configurationSource);
It does seem to load the file as when I .toString() it, it shows that it has loaded the number of bytes - which happens to be the size of the config file. None of it works though. All logging goes to stdout. So it's loading, but not taking affect.
Configurator.initialize
only works before the LoggerContext
is created.
It should work in the static block were you set the log4j2.configurationFile
property. If for some reason you need before loading the configuration file, you need to use Configurator.reconfigure
.