加载XML配置文件时出现Log4j2错误

我正在尝试使用嵌入在我的Java应用程序中的Log4j2的XML配置文件,但是不起作用。

代码:

ConfigurationSource source = new ConfigurationSource(Main.class.getResourceAsStream("/in/gunbound/prelauncher/server/log4j2/log4j2.xml")); ConfigurationFactory factory = (ConfigurationFactory) XMLConfigurationFactory.getInstance().getConfiguration(source); ConfigurationFactory.setConfigurationFactory(factory); 

错误:

线程“main”中的exceptionjava.lang.ClassCastException:org.apache.logging.log4j.core.config.XMLConfiguration无法强制转换为in.gunbound.prelauncher.server中的org.apache.logging.log4j.core.config.ConfigurationFactory .Main.main(Main.java:62)

使用XML配置文件时,不需要使用ConfigurationFactory。 只需确保您的XML文件设置正确。

文件名必须是log4j2.xml

该文件必须添加到classPath中。

在应用程序中获取具有正确名称的记录器,与您在xml文件中设置记录器的名称相同,请查看此处 。

我有类似的问题。 以下示例帮助了我: https : //svn.apache.org/repos/asf/logging/log4j/log4j2/trunk/core/src/test/java/org/apache/logging/log4j/FormatterLoggerManualExample.java

在你的情况下,它应该是这样的:

 URI configuration = Main.class.getResource("/in/gunbound/prelauncher/server/log4j2/log4j2.xml").toURI(); Configurator.initialize("config", null, configuration); 

有同样的问题,解决它像这样:

 import java.io.InputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationFactory.ConfigurationSource; import org.apache.logging.log4j.core.config.XMLConfigurationFactory; public class Log { private Logger logger; public Log(String name) { InputStream is = Application.class.getResourceAsStream("log-config.xml"); ConfigurationSource source = new ConfigurationSource(is); Configuration config = XMLConfigurationFactory.getInstance().getConfiguration(source); LoggerContext ctx = (LoggerContext) LogManager.getContext(true); ctx.stop(); ctx.start(config); logger = ctx.getLogger(name); } public Logger getLog() { return logger; } } 

我目前正在使用带有databaseAppender的log4j2 beta 9来写入ora db。

最短路径(不创建工厂,源或url对象):

 Configurator.initialize("configName", "logging.xml"); 

即使配置文件未命名为“log4j2。*”,这也可以工作。