Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getSimpleName() vs getName() for acquiring logger

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?

like image 465
kuriouscoder Avatar asked Nov 29 '10 22:11

kuriouscoder


People also ask

What is Getclass () getName () in Java?

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.

What is the use of Class getSimpleName?

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.


4 Answers

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 
like image 90
kdabir Avatar answered Oct 02 '22 22:10

kdabir


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 
like image 34
user2481237 Avatar answered Oct 02 '22 21:10

user2481237


Using of this.getClass().getName();

Returns : alin.iwin.flickrbrowser.GetRawData

Meanwhile

private String LOG_TAG = this.getClass().getSimpleName();

Return only : GetRawData.

like image 40
Coman Avatar answered Oct 02 '22 21:10

Coman


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.

like image 21
Eyal Schneider Avatar answered Oct 02 '22 20:10

Eyal Schneider