如何检测丢失的LOG4J2配置?

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

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