How to specify Log4J 2.x config location?

2019-01-18 11:08发布

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?

4条回答
Animai°情兽
2楼-- · 2019-01-18 11:28

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楼-- · 2019-01-18 11:43

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
查看更多
闹够了就滚
4楼-- · 2019-01-18 11:46

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);
查看更多
乱世女痞
5楼-- · 2019-01-18 11:48

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);
查看更多
登录 后发表回答