I want to load Log4j2 XML configuration file programmatically from my application.
Tried this:
ConfigurationSource source = new ConfigurationSource()
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);
}
If you config with .properties file:
String propertiesFile = "./test/Configuration/log4j2.properties";
ConfigurationSource source = new ConfigurationSource(new FileInputStream(propertiesFile), new File(propertiesFile));
Configurator.initialize(null, source);
Found the answer myself. Someone might find it useful.
ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
source.setFile(new File(logConfigurationFile));
source.setInputStream(new FileInputStream(logConfigurationFile));
Configurator.initialize(null, source);
Below worked for me, Log4j2 with SLF4J wrapper:
public class MyClass {
static {
try {
InputStream inputStream = new FileInputStream("C:/path/to/log4j2.xml");
ConfigurationSource source = new ConfigurationSource(inputStream);
Configurator.initialize(null, source);
} catch (Exception ex) {
// Handle here
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class); // LogManager if not using SLF4J
public void doSomething() {
LOGGER.info(...)
}
}
static {
File log4j2File = new File("C:/path/to/log4j2.xml");
System.setProperty("log4j2.configurationFile", log4j2File.toURI().toString());
}
Need toURI()
to follow File URI Scheme format, else it throws MalformedURLException
.
Sources:
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);
final URL log4j = Resources.getResource("log4j2-test.xml");
LoggerContext.getContext(false)
.start(new XmlConfiguration(new ConfigurationSource(
Resources.asByteSource(log4j).openStream(),
log4j)));