In Java, why is it best practice to declare a logger static final?
private static final Logger S_LOGGER
In Java, why is it best practice to declare a logger static final?
private static final Logger S_LOGGER
Ideally Logger should be as follows upto Java 7, for giving no Sonar and giving a Compliant Code: private: never be accessible outside of its parent class. If another class needs to log something, it should instantiate its own logger. static: not be dependent on an instance of a class (an object). When logging something, contextual information can of course be provided in the messages but the logger should be created at class level to prevent creating a logger along with each object and hence preventing High Memory footprint. final: be created once and only once per class.
According to the info I read on the internet about making the logger static or not, the best practice is to use it according to the use cases.
There are two main arguments:
When you make it static, it is not garbage collected (memory usage & performance).
When you don't make it static it is created for each class instance (memory usage)
Thus, When you are creating a logger for a singleton, you don't need to make it static. Because there will be only one instance thus one logger.
On the other hand, if you are creating a logger for a model or entity class, you should make it static not to create duplicated loggers.
We use
private - so that it remains a private data member for the class (which we usually want for every class level variable).
static - this is important. We want a single logger instance for the entire class and not that every new instance/object of the class spawns a new logger. Static key word in java is made for the same. Hence we declare it static
final - we don't want to change the value of our logger variable, rather we want it to remain constant for the entire class lifecycle.
Actually static loggers can be "harmful" as they are supposed to work in a static context. When having a dynamic environment eg. OSGi it might help to use non-static loggers. As some logging implementations do a caching of loggers internally (AFAIK at least log4j) the performance impact might negligible.
One drawback of static loggers is eg. garbage collection (when a class is used only once eg. during initialization the logger will be still kept around).
For more details check:
See also: