Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to declare logger variable in java

Tags:

java

logging

I just wantd to know which is the best way declare logger variable in java. Following are some declaration.

1> private static final Logger logger = Logger.getLogger(ServiceImpl.class);

2> private static Logger logger = Logger.getLogger(ServiceImpl.class);

3> private static final Logger LOGGER= Logger.getLogger(ServiceImpl.class);

4> private static Logger LOGGER= Logger.getLogger(ServiceImpl.class);

P.S I really appreciate if anybody knows another best alternative ways to declare looger variable.

like image 978
Raje Avatar asked Jan 06 '12 10:01

Raje


People also ask

How do you write a logger in Java?

The process of creating a new Logger in Java is quite simple. You have to use Logger. getLogger() method. The getLogger() method identifies the name of the Logger and takes string as a parameter.

Should loggers 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.

Where do we use logger in Java?

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.

Which method is used to find or create a logger with the name passed as a parameter?

getLogger(java. lang. String): This method is used to find or create a logger with the name passed as parameter.


2 Answers

All upper-case variable names are IMO out because you really aren't declaring/defining a constant but a static variable. Uppercase names are more suitable for "constants". That said, I'd personally go with the first approach.

private static final Logger logger = Logger.getLogger(ServiceImpl.class);
like image 111
Sanjay T. Sharma Avatar answered Oct 27 '22 14:10

Sanjay T. Sharma


I vote for 3

 private static final Logger LOGGER = Logger.getLogger(ServiceImpl.class);

It's final since you don't change it and it's in uppercase since it's a constant.

like image 45
Stan Kurilin Avatar answered Oct 27 '22 15:10

Stan Kurilin