Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should be logger always final and static?

Class can be accessed from many threads. Must be logger in this case also be final and static? Thanks.

like image 311
user710818 Avatar asked Sep 06 '11 18:09

user710818


People also ask

Should logger always be static?

Loggers should be declared to be static and final. It is good programming practice to share a single logger object between all of the instances of a particular class and to use the same logger for the duration of the program.

Why do we declare logger static final?

private static final Logger log = LoggerFactory. getLogger(Foo. class); The former way allows you to use the same logger name (name of the actual class) in all classes throughout the inheritance hierarchy.

Should logger be all caps?

If your coding standards - if you have any - say that it should be uppercase then yes.

What is the purpose of creating a logger?

A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.


2 Answers

All major java logging packages (java.util.logging, log4j, etc.) are synchronized and thread safe. The standard pattern of a private final static logger per class is fine even if the class is called from multiple threads.

like image 70
ataylor Avatar answered Sep 21 '22 02:09

ataylor


Yes the logger should be static and final. Also preferably private. There needs be only one logger instance per class and also unless you are going to change the log preference dynamically, it is better to make it final.

Logger are thread safe and you do not have to worry about threading.

like image 39
uncaught_exceptions Avatar answered Sep 20 '22 02:09

uncaught_exceptions