22

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?

kuriouscoder
  • 5,394
  • 7
  • 26
  • 40

5 Answers5

25

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
kdabir
  • 9,623
  • 3
  • 43
  • 45
23

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
user2481237
  • 299
  • 2
  • 3
6

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

Returns : alin.iwin.flickrbrowser.GetRawData

Meanwhile

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

Return only : GetRawData.

Coman
  • 61
  • 1
  • 1
5

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.

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
2

You might get confused if you have many classes with the same simpleName in different packages. Having many loggers with the same name should not be a problem otherwise - just could be confusing.

Armand
  • 23,463
  • 20
  • 90
  • 119