While working with Java applications, you may already see a logger object defined like below.
private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);
Why is the logger instance defined as private?
Usually, logger instances are specific to a class, no point in making these available to outside of the class. So, it is recommended to make them private.
Why is the logger instance defined with static specifier?
In general, we use the class name to log the log messages like below. Adding a class name helps in identifying the error easily.
Nov 03, 2021 5:12:20 PM com.sample.app.AppConfig main WARNING: No default configurations set for the app readtime out
In memory footprint point of view also, if the logger is defined as static, only one logger instance is created and used by all the other references of given class, whereas an instance logger member will cost a variable reference for every instance of the class.
If your class is implementing Serializable interface, all instance properties are serialized by default. If you do not make the logger as static, you need to explicitly add transient keyword to the logger instances wherever you used.
In summary, static logger variables will take less memory footprint, and less CPU overhead.
Why is the logger instance defined with final specifier?
Once a logger instance is defined, usually we do not change the properties of it during the application lifetime. So, it is defined with final.
Reference
http://slf4j.org/faq.html#declared_static
You may like
Java: How to find the minimum element in a collection?
Java: Get the index of first occurrence of a substring
Java: Get the index of last occurrence of a substring
No comments:
Post a Comment