I've seen code that uses log4j
, which acquires logger
for a given Logger
using
static public Logger getLogger(String name)
and
static public Logger getLogger(Class clazz)
with the former api passed explicitly with getSimpleName()
, while the latter uses getName()
on the passed Class
. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?
The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.
getSimpleName() returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.
Yes there is a huge difference.
I never use simpleName
for Logger
instance as it strips down the package name. Apart from having problems when same class name exists in two different packages (leading to both classes getting the same logger instance), you lose the ability to control logger inheritance.
e.g. for two loggers:
com.foo.A com.foo.B
in properties, i can just have:
log4j.logger.com.foo=DEBUG,CONSOLE
E.g. My class ShapeDemo.java resides in com.test package, and I have written code like below.
System.out.println("Name-->"+ShapeDemo.class.getName()); System.out.println("SimpleName-->"+ShapeDemo.class.getSimpleName());
This will output following
Name-->com.test.ShapeDemo SimpleName-->ShapeDemo
Using of this.getClass().getName();
Returns : alin.iwin.flickrbrowser.GetRawData
Meanwhile
private String LOG_TAG = this.getClass().getSimpleName();
Return only : GetRawData.
I prefer using the full name (Class.getName()). When packages are organized correctly, this allows tuning log4j to handle differently log messages originating from different parts of the java packages tree.
For example, you can easily configure all classes in packages starting with "com.mycompany.infra" to use a specific appender, and log only messages of level WARN or above.
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