user648026 user648026 - 1 year ago 87
Java Question

Generic way of getLogger from log4j.Logger

Instead of specifying the class name on each class:

log = Logger.getLogger(Foo.class);
log = Logger.getLogger(Bar.class);
log = Logger.getLogger(Test.class);

Will it be OK to use :

log = Logger.getLogger(this.getClass());

What will be the implications?

Answer Source

If you create a subclass, the log messages will get logged to the subclass's logger.

package pkgone;
public class SuperType {
    private Logger log = Logger.getLogger(this.getClass());
    public void someAction() {"Doing something");


package pkgtwo;
import pkgone.SuperType;
public class SubType extends SuperType {
    // for instances of SubType, the log object in SuperType
    // will get initialized with SubType's class object


// some code somewhere that uses SubType
SubType obj = new SubType();

In the above example, "Doing something" will get logged to the pkgtwo.SubType logger instead of pkgone.SuperType logger, which may or may not be what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download