I want to load Log4j2 XML configuration file programmatically from my application.
Tried this:
ConfigurationSource source = new ConfigurationSource(); source.setLocation(logConfigurationFile); Configurator.initialize(null, source);
and this:
ConfigurationSource source = new ConfigurationSource(); source.setLocation(logConfigurationFile); ConfigurationFactory factory = (ConfigurationFactory) XMLConfigurationFactory.getInstance().getConfiguration(source); ConfigurationFactory.setConfigurationFactory(factory);
But nothing works yet.
We should put log4j2. xml anywhere in the application's classpath. Log4j will scan all classpath locations to find out this file and then load it. We can find this file mostly placed in the 'src/main/resources' folder.
Sample log4j Configuration Files During Content Engine installation, two log4j sample files are placed on the system in the ContentEngine\config\samples\ folder: log4j. properties. client: A Java format file that contains client configuration settings.
Configuration of Log4j 2 can be accomplished in 1 of 4 ways: Through a configuration file written in XML, JSON, YAML, or properties format. Programmatically, by creating a ConfigurationFactory and Configuration implementation.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With