Java 以编程方式加载 Log4j2 配置文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21083834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load Log4j2 configuration file programmatically
提问by HashimR
I want to load Log4j2 XML configuration file programmatically from my application.
我想从我的应用程序以编程方式加载 Log4j2 XML 配置文件。
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.
但还没有任何效果。
采纳答案by HashimR
Found the answer myself. Someone might find it useful.
自己找到了答案。有人可能会发现它很有用。
ConfigurationSource source = new ConfigurationSource();
source.setLocation(logConfigurationFile);
source.setFile(new File(logConfigurationFile));
source.setInputStream(new FileInputStream(logConfigurationFile));
Configurator.initialize(null, source);
回答by dcompiled
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.
如果您只有一个主要入口点,此代码片段可能会为您省去一些麻烦。必须在创建任何记录器之前触发 set 属性调用。这种方法适用于类路径上的文件。
public class TestProcess {
static {
System.setProperty("log4j.configurationFile", "log4j-alternate.xml");
}
private static final Logger log = LoggerFactory.getLogger(TestProcess.class);
}
回答by switch_java3
For the newest version of log4j, here is what should work for loading an external log4j2.xml
:
对于最新版本的 log4j,以下是加载外部文件的方法log4j2.xml
:
String log4jConfigFile = System.getProperty("user.dir") + File.separator + "log4j2.xml";
ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4jConfigFile));
Configurator.initialize(null, source);
回答by lanoxx
If you are using a Servlet 3.0 Web Applicationyou can use the Log4jServletContextListenerand do the following:
如果您使用的是Servlet 3.0 Web 应用程序,则可以使用Log4jServletContextListener并执行以下操作:
Write a custom LogContextListener
which extends from Log4jServletContextListener
, set it up in your web.xml
and disable auto initialization:
编写一个LogContextListener
从 扩展的自定义,Log4jServletContextListener
在您的中进行设置web.xml
并禁用自动初始化:
<listener>
<listener-class>com.example.LogContextListener</listener-class>
</listener>
<context-param>
<param-name>isLog4jAutoInitializationDisabled</param-name>
<param-value>true</param-value>
</context-param>
In your custom LogContextListener
overwrite contextInitialized
and set the config location
在您的自定义LogContextListener
覆盖contextInitialized
并设置配置位置
public void contextInitialized(ServletContextEvent event) {
/* Some logic to calculate where the config file is saved. For
* example you can read an environment variable.
*/
String pathToConfigFile = ... + "/log4j2.xml";
Configurator.initialize(null, pathToConfigFile);
super.contextInitialized(event);
}
The advantage over configuring the location directly in the web.xml
is that
you can compute the path based on some additional information and access the log4j2.xml even if its outside of your classpath.
直接在 中配置位置的优点web.xml
是您可以根据一些附加信息计算路径并访问 log4j2.xml,即使它在您的类路径之外。
回答by TJR
final URL log4j = Resources.getResource("log4j2-test.xml");
LoggerContext.getContext(false)
.start(new XmlConfiguration(new ConfigurationSource(
Resources.asByteSource(log4j).openStream(),
log4j)));
回答by myset
Considering - https://logging.apache.org/log4j/2.x/log4j-core/apidocs/org/apache/logging/log4j/core/config/Configurator.html
Configurator.initialize(null, "classpath:conf/logger.xml");
or
Configurator.initialize(null, "/full_path/conf/logger.xml");
Be aware and does not use both at the same time.
请注意,不要同时使用两者。
回答by silver
Below worked for me, Log4j2 with SLF4Jwrapper:
下面对我有用,带有SLF4J包装器的Log4j2 :
Solution 1:
解决方案1:
public class MyClass {
static {
try {
InputStream inputStream = new FileInputStream("C:/path/to/log4j2.xml");
ConfigurationSource source = new ConfigurationSource(inputStream);
Configurator.initialize(null, source);
} catch (Exception ex) {
// Handle here
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class); // LogManager if not using SLF4J
public void doSomething() {
LOGGER.info(...)
}
}
Solution 2:
解决方案2:
static {
File log4j2File = new File("C:/path/to/log4j2.xml");
System.setProperty("log4j2.configurationFile", log4j2File.toURI().toString());
}
Need toURI()
to follow File URI Scheme format, else it throws MalformedURLException
.
需要toURI()
遵循File URI Scheme 格式,否则会抛出MalformedURLException
.
Sources:
资料来源:
回答by tiboo
If you config with .properties file:
如果您使用 .properties 文件进行配置:
String propertiesFile = "./test/Configuration/log4j2.properties";
ConfigurationSource source = new ConfigurationSource(new FileInputStream(propertiesFile), new File(propertiesFile));
Configurator.initialize(null, source);