我正在尝试为我的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”中的异常java.lang.ClassCastException: org.apache.logging.log4j.core.config.XMLConfiguration无法强制转换 到org.apache.logging.log4j.core.config.ConfigurationFactory at in.gunbound.prelauncher.server.Main.main(Main.java:62)
答案 0 :(得分:2)
使用XML配置文件时,您不需要使用ConfigurationFactory
。只需确保您的XML文件设置正确。
文件名必须为log4j2.xml
我必须将文件添加到classPath。
在应用程序中获取具有正确名称的记录器,与您在xml文件中设置记录器的名称相同,具有look here。
答案 1 :(得分:2)
我有类似的问题。以下示例帮助了我: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);
答案 2 :(得分:2)
遇到同样的问题,解决了这个问题:
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。
答案 3 :(得分:0)
最短路径(不创建工厂,源或url对象):
Configurator.initialize("configName", "logging.xml");
即使配置文件未命名为“log4j2。*”。
,也可以