I want to load Log4j2 XML configuration file programmatically from my application.
Tried this:
ConfigurationSource source = new ConfigurationSource()
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: