Putting Logger.info in static block

2019-06-18 00:52发布

问题:

I have the following class

public class MyClass
{
    private static final Logger logger = Logger.getLogger(MyClass.class);

    static
    {
        logger.info("some text");
    }
}

Is it safe to assume that by the time we reach logger.info, the log4j system is initialized and is ready to emit logs?

It seems that if I am able to do a Logger.getLogger() and get back a valid Logger instance, it means that Log4j is initialized, right?

回答1:

Yes, it is. Static initializers (that is, both static {} blocks and initial assignments to static variables) are executed in the order they are declared.

Default initialization of log4j relies on a static block in a log4j class LogManager that is executed once Logger class is loaded, and it is loaded prior to its first use. This is why your construction works.



回答2:

See this part of the JLS. It talks about what happens when you initialise a class. This part talks about static initialisers. In answer to your question then AFAIK the static blocks are executed in the order they occur. They will be executed when the class is loaded which can happen when you create an instance of it or access a static var/method of it.



标签: java log4j