Reputation: 1321
We have "private static final" instances of Log4j/commons logging in all service/utility classes (spring singleton beans.)
I am wondering if there is any reasonable case to have those objects "static final" if (1) there are no static methods that use it (2) classes are singletons?
I assume in either static instance or non-static property of a singleton objects - this would be the same old-gen object for JVM. Also I think JVM can easily identify an object if it is private and never changes for any performance purposes (if there are even any).
Is it correct?
Thanks!
Upvotes: 1
Views: 1549
Reputation: 201439
It's a common idiom to make the logger static
and final
, and it's easy to start a code review does the "standard" logger stanza appear. I would see no reason to deviate from the idiom in a singleton, but you are correct that it would only create one logger
in the case of a singleton.
Upvotes: 1
Reputation: 709
I, personally always create a private static final Logger LOGGER = LogManager.getLogger();
as the first line in ANY class I create (Spring beans, DAOs, inner classes, domain objects, etc). LogManager acts as a factory for my individual Logger objects:
https://logging.apache.org/log4j/2.x/log4j-api/apidocs/org/apache/logging/log4j/LogManager.html
I follow this so much that my projects settings under Eclipse actually generates that line anytime I create a class.
When a logger is created, it references a name or a class to log under, the factory method I referenced above creates the logger with the specific class that it is contained in.
This practice becomes very useful when you want to adjust your log4j configuration. You can add highly or lowly qualified loggers at different levels or route to different files. There are a lot of possibilities for what you can do with the framework.
As for private static final, my reasoning for it are as follows:
Hope this helps! :)
Upvotes: 3