【发布时间】:2017-10-28 21:26:14
【问题描述】:
我正在尝试Initialize Log4j by Combining Configuration File with Programmatic Configuration。
我遵循了手册(虽然它的语法不太正确并且已经过时),结果产生了以下类:
CustomConfigurationFactory.java:
package factory;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Order;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import java.net.URI;
@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(1)
public class CustomConfigurationFactory extends ConfigurationFactory {
/**
* Valid file extensions for XML files.
*/
private static final String[] SUFFIXES = new String[]{".xml", "*"};
/**
* Return the Configuration.
*
* @param source The InputSource.
* @return The Configuration.
*/
public Configuration getConfiguration(LoggerContext context, ConfigurationSource source) {
return new CustomConfiguration(context, source);
}
/**
* Returns the file suffixes for XML files.
* @return An array of File extensions.
*/
public String[] getSupportedTypes() {
return SUFFIXES;
}
}
CustomConfiguration.java:
package factory;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import java.util.Map;
public class CustomConfiguration extends XmlConfiguration {
CustomConfiguration(LoggerContext context, ConfigurationSource configSource) {
super(context, configSource);
}
@Override
protected void doConfigure() {
super.doConfigure();
final LoggerConfig rootLogger = getRootLogger();
final Map<String, Appender> appenderMap = rootLogger.getAppenders();
if (MainClass.DEBUG) {
rootLogger.addAppender(appenderMap.get("Console"), Level.ALL, null);
} else {
rootLogger.addAppender(appenderMap.get("Mail"), Level.ERROR, null);
}
}
}
现在,当运行此程序并在对 Logging API 进行任何调用之前调用 ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory()) 时,我会以
ERROR StatusLogger Reconfiguration failed: No configuration found for 'someNumbersAndChars' at 'null' in 'null'
在调试时,我发现这是在我第一次获取Logger 时打印的。原因是,如果提供了自定义 ConfigurationFactory,ConfigurationFactory 的私有子类 Factory(这是默认工厂)对 ConfigurationFactory.getConfiguration(LoggerContext, String, URI) 的实现将被 ConfigurationFactory 的实现覆盖.
如果 URI 是这样,ConfigurationFactory 的实现只返回 null,而 ConfigurationFactory.Factory 的实现仍然返回一个有效的配置。
我现在的第一个想法是在我的自定义工厂中覆盖 ConfigurationFactory.getConfiguration() 的这些重载,但必须有另一种方法,对吧? ;)
【问题讨论】:
标签: java debugging logging log4j2