Putting Logger.info in a static block

I have the following class

public class MyClass { private static final Logger logger = Logger.getLogger(MyClass.class); static { logger.info("some text"); } } 

Can we assume that by the time logger.info reached, the logger.info system is initialized and ready to emit logs?

It seems that if I can do Logger.getLogger() and return a valid instance of Logger, that means Log4j is initialized, right?

+7
source share
2 answers

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

The default initialization for log4j is based on a static block in the LogManager class LogManager , which is executed after loading the Logger class, and it is loaded before its first use. That is why your construction work.

+6
source

See this part of JLS . It talks about what happens when you initialize a class. This part talks about static initializers. In response to your question, AFAIK, static blocks execute in the order in which they occur. They will be executed when the class is loaded, which can happen when you instantiate it or access the static var / method from it.

0
source

All Articles