Should loggers be declared static?
In is the traditional log4j usage pattern
import org.apache.log4j.Logger; public class MyClass { final static Logger logger = Logger.getLogger("some.name"); MyClass() { } public void foo() { logger.debug("Hello world."); ... }
should the logger instance declared as static?
First answer
Yes it should because it is not good to let on Log4J implementation to keep information about all classes. Log4J can return singleton instances but it is not a rule!
It is very good idea to keep this static. At least this save one reference in memory or (if Log4J doesn't return singletons) or if the implementation doesn't care about one instance for one class (most do) that can save lot of memory and cpu time. If you do not declare it static every class instance will have it` own logging instance.
Second and correct answer
- It depends. In all existing and foreseeable implementations of log4j, in the following code
Logger x = Logger.getLogger("wombat"); Logger y = Logger.getLogger("wombat");both x and y will refer to the exact same logger instance. Thus, declaring the logger object does not result in a gain of the space occupied by a new logger object but only in a gain of the space occupied by the reference to a logger instance.
A reference to a logger will cost about 4 bytes more per instance of MyClass, a minor overhead indeed.
If the logger variable is an instance variable, then the Logger.getLogger method will be invoked for each instance of MyClass. It takes less then 10 nanoseconds for the Logger.getLogger instance to retrieve an existing logger instance. Again, a negligible overhead in most situations.
Discussion
With static loggers I'll immediately run into naming problems. It's common to use class names instead of inventing "some name"? The issue Creating Loggers DRY-ly is discussing this problem. Any comments?