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.
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.
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.
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.
You can always use any string as logger name other than class type. It's definitely ok.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With