How to specify Log4J 2.x config location?

2019-01-18 11:21发布

问题:

Is there any way to specify Log4J 2.x log4j2.xml file location manually (like DOMConfigurator in Log4J 1.x), without messing with classpath and system properties?

回答1:

You could use the static method #initialize(String contextName, ClassLoader loader, String configLocation) (see source here) in org.apache.logging.log4j.core.config.Configurator. (You can pass null for the class loader.)

Be aware that this class is not part of the public API so your code may break with any minor release.

For completeness, you can also specify the location of the configuration file with this system property:

-Dlog4j.configurationFile=path/to/log4j2.xml


回答2:

In Windows, be aware that you need to use a URI with the log4j.configurationFile property

-Dlog4j.configurationFile=file://C:\path\to\log4j2.xml


回答3:

Using the LoggerContext allows to setConfigLocation.

File f = new File(this.logConfigFile);
URI fc = f.toURI();         
System.out.println("Loading logging config file: " + fc);
Logger l = (Logger) LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
l.getContext().setConfigLocation(fc);

or alternatively

LoggerContext.getContext().setConfigLocation(java.net.URI);


回答4:

You can initialize like below as well

ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4j file Path));
XmlConfiguration xmlConfig = new XmlConfiguration(source);
Logger logger = (Logger) LogManager.getLogger(); 
logger.getContext().start(xmlConfig); 

In each class you can get logger instance as below

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

private final Logger logger = LogManager.getLogger(ABC.class);