java – 如何检测丢失的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,请参阅documentation for Log4j2配置:

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

上一篇:java – Log4j2自定义appender:ERROR尝试追加到非启动的appender


下一篇:log4j2用Log4jContextSelector启动参数配置全局异步日志是如何使用disruptor