Search code examples
javalogginglog4jslf4jreload4j

How can I check if SLF4J with Reload4J is initialized?


We are switching from plain Log4J (with reload4j) to using SLF4J. In one bit of code we have a check if the logging framework is initialized. The goal behind that check is to have a fallback to printing to System.err in case there's something to log before logging system initialization.

private static boolean isLoggerInitialized() {
    return LOGGER.getParent().getAllAppenders().hasMoreElements();
}

This is not possible with SLF4J anymore. Thus I am searching for an alternative to check the initialization state of SLF4J.


Solution

  • SLF4J is a generic logging API that is implemented by various logging frameworks, (eg Logback, Log4j2, etc), so while the answer slightly depends on which implementation you're using, all modern logging implementations do not require "initialization"; they're ready to use as soon as they're declared, so your solution is:

    private static boolean isLoggerInitialized() {
        return true;
    }
    

    If you're using Spring starter libraries, the default logging library is Logback. You can chose something else by including a different Slf4j compliant logging library (all the main ones are compliant) in your class path. As far as "initialization" goes, it doesn't matter what you choose if you choose a mainstream one.

    Rather than code the declaration of your logger, I recommend using one of the Lombok logging annotations, with which your code becomes just:

    @Slf4j
    public class MyClass {
    
        public someMethod() {
            log.info("Hello world");
        }
    
    }
    

    The declaration of the log field is done for you (and is instantly ready to use).