Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why log4j's Logger.getLogger() need pass a Class type?

Tags:

java

log4j

I read some articles about how to use log4j. Most of them give below code as a beginning:

 Logger logger = Logger.getLogger("com.foo.Bar"); 

or

 Logger logger = Logger.getLogger(XXX.class); 

This will initialize the logger object.But my question is why need send the class type as a parameter? It seems when I use the logger, I don't care in which class I use it.So the Class type seems no effect to logger. If I declare a logger as static and public, I can call this logger at another class, So what's the intention of the author to design it like this? Will the Class type bind something when I use the logger? Or I can send any Class types to the getLogger function.

like image 840
roast_soul Avatar asked Jan 30 '13 04:01

roast_soul


People also ask

What is logger getLogger ()?

getLogger(java. lang. String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name.

What is log4j logger used for?

log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License. log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages. log4j is highly configurable through external configuration files at runtime.

Does logger need to 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.


1 Answers

  1. You can always use any string as logger name other than class type. It's definitely ok.

  2. The reason why many people use class type, I guess:

    • Easy to use. You don't need to worry about logger name duplication in a complex Java EE application. If other people also use your logger name, you may have a log file including no only the output of your class;

    • Easy to check the logging class, as the logger name will show in the log file. You can quickly navigate to the specific class;

    • When you distribute you class, people may want to redirect the logging from your class to a specific file or somewhere else. In such case, if you use a special logger name, we may need to check the source code or imposssible to do that if souce is unavailable.

like image 84
Jintian DENG Avatar answered Sep 20 '22 01:09

Jintian DENG