How to specify Log4J 2.x config location?

我的未来我决定 提交于 2019-11-28 09:49:46

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

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

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

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);

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);

If you are using log4j2 and properties are in defined in log4j2.properties file then use this.

-Dlog4j2.configurationFile=file:/home/atul/log4j2.properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!