Generic way of getLogger from log4j.Logger

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.


Try this way to look up a generic class...

private static final Log LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass());

The best part is you can use this method statically.

Tags:

Java

Log4J