How to detect missing LOG4J2 config?

2019-02-23 19:39发布

问题:

I would like to be able to detect when the app is missing a LOG4J2.XML configuration file, and in that case set some other defaults than what LOG4J2 has otherwise.

Basically, I would like to run this code if a config file isnt found:

    // 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.        

How can I detect that LOG4J2 failed to load a configuration?

回答1:

Seems like ...

if (config instanceof DefaultConfiguration)

...would be enough, since DefaultConfiguration is used whenever there is nothing else available, see the documentation for Log4j2 configuration:

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



标签: java log4j2