Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting Logger.info in static block

Tags:

java

log4j

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?

like image 843
Swaranga Sarma Avatar asked Sep 18 '12 16:09

Swaranga Sarma


1 Answers

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.

like image 54
MaDa Avatar answered Nov 09 '22 03:11

MaDa