Java 如何检测丢失的LOG4J2配置?

Java 如何检测丢失的LOG4J2配置?,java,log4j2,Java,Log4j2,我希望能够检测应用程序何时缺少LOG4J2.XML配置文件,并在这种情况下设置一些其他默认值,而不是LOG4J2的其他默认值 基本上,如果找不到配置文件,我希望运行以下代码: // A default configuration that shows ALL Logger output, without a XML config! LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Confi

我希望能够检测应用程序何时缺少LOG4J2.XML配置文件,并在这种情况下设置一些其他默认值,而不是LOG4J2的其他默认值

基本上,如果找不到配置文件,我希望运行以下代码:

    // A default configuration that shows ALL Logger output, without a XML config!
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); 
    loggerConfig.setLevel(Level.ALL);
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.        
如何检测LOG4J2未能加载配置?

似乎

if (config instanceof DefaultConfiguration)
…就足够了,因为只要没有其他可用的配置,就会使用DefaultConfiguration,请参阅日志4J2配置:

如果找不到配置文件,则
DefaultConfiguration
将使用。这将导致日志输出转到控制台


只是一个猜测,但是如果(config instanceof DefaultConfiguration)可能会起到作用。这很聪明,添加它作为答案,我会选择它。当在类路径中找到LOG4J2.XML时,config是XmlConfiguration的一个实例,否则为DefaultConfiguration。请注意,如果您发现getContext()方法不存在的错误,您需要将org.apache.logging.log4j.spi.LoggerContext导入替换为org.apache.logging.log4j.core.LoggerContext对于大多数人来说,使用默认值就足够了,而无需额外配置,但是DefaultConfiguration也设置为跳过调试级别的条目,这在本例中是我想要的。