Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Log4j2 configuration file programmatically

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.

like image 271
HashimR Avatar asked Jan 13 '14 04:01

HashimR


People also ask

Where do I put my log4j2 XML file?

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.

Where is log4j configuration file?

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.

What is log4j2 configuration file?

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.


2 Answers

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); 
like image 175
switch_java3 Avatar answered Sep 23 '22 08:09

switch_java3


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);  } 
like image 41
dcompiled Avatar answered Sep 21 '22 08:09

dcompiled