Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically verify that log4j 2 was properly configured?

Tags:

java

log4j2

From reading the log4j 2 documentation it is expected that the configuration will be loaded if the appropriate configuration file is in classpath. But I need to know for sure that the configuration file was properly processed. Is there a way I can verify that the configuration file I expected to be loaded was in fact found and successfully loaded?

I am writing code that will be used by other developers and it could be the case that log4j 2, which is integral to the library we are writing, was not properly configured, because the file was not in classpath or misconfigured. If log4j 2 is not properly configured than I must halt further processing of our library, it must spit out major errors and big deal must be made about it. I cannot let the code continue. So the bottom-line, I need to know that log4j 2 properly processed the expected configuration file.

Also, I would prefer to use the log4j 2 API and not the Core library, but if Core is the only way then so be it.

like image 256
Jose Martinez Avatar asked May 19 '14 21:05

Jose Martinez


1 Answers

You can do some verification using just the api: you can register a StatusListener with the StatusLogger. The StatusLogger is used internally by Log4J to log details internal to Log4J. Most of this internal logging is related to configuration.

For example:

public class HaltingStatusListener implements StatusListener {
    public Level getStatusLevel() {
        return Level.ERROR;
    }
    public void log(StatusData data) {
        throw new BigDealException("Internal log4j error detected: "
                + data.getMessage());
    }
}

This may not be sufficient for your needs though. Another thing you could check:

LoggerContext context = LogManager.getContext();
if (context instanceof SimpleLoggerContext) {
    throw new BigDealException(
            "Log4j did not find config file & uses default setup");
}

If you want to go into more detail and verify appenders/loggers etc you will need to use the core classes. In that case please send a message to the log4j-user mailing list to get the other team members involved.

UPDATE: The Log4J team currently assumes that Log4J initialization failure is not critical and should not halt the application. You can ask for an enhancement where log4j does halt the application (throw an exception) if for example the core jar was not found or if no configuration file was found. You can either raise a Jira ticket for this or ask on the mailing list.

like image 50
Remko Popma Avatar answered Oct 25 '22 11:10

Remko Popma