Drahakar Drahakar - 3 months ago 35
Java Question

Should logger be private static or not

Should logger be declared static or not? Usually I've seen two types of declaration for a logger :

protected Log log = new Log4JLogger(aClass.class);


private static Log log = new Log4JLogger(aClass.class);

Which one should be used? what are the pro's and con's of both?


The advantage of the non-static form is that you can declare it in an (abstract) base class like follows without worrying that the right classname will be used:

protected Log log = new Log4JLogger(getClass());

However its disadvantage is obviously that a whole new logger instance will be created for every instance of the class. This may not per se be expensive, but it adds a significant overhead. If you'd like to avoid this, you'd like to use the static form instead. But its disadvantage is in turn that you have to declare it in every individual class and take care in every class that the right classname is been used during logger's construction because getClass() cannot be used in static context. However, in the average IDE you can create an autocomplete template for this. E.g. logger + ctrl+space.

On the other hand, if you obtain the logger by a factory which in turn may cache the already-instantiated loggers, then using the non-static form won't add that much overhead. Log4j for example has a LogManager for this purpose.

protected Log log = LogManager.getLogger(getClass());