user648026 user648026 - 2 days ago 5
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

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() {
        log.info("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();
obj.someAction();

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.

Comments