如何检测丢失的 LOG4J2 配置?

How to detect missing LOG4J2 config?

我希望能够检测到应用程序何时缺少 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,请参阅 documentation 了解 Log4j2 配置:

If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.