views:

146

answers:

3

Rational

I would like to have more detailed logging debugging/logging output on a few superclasses, so the subclass name will not actually be effecting real-time performance nor application logic. I'm also of the opinion that it is fairly bad design to do this normally, however I really do want this info to be logged during development runs.

Question

Suppose I have a simple class structure as below, how do I pull the name of the subclass into the superclass without having to explicitly pass a reference?

public abstract AbstractClass {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public AbstractClass() {}

    public void execute(ContextObject context) {
        if (logger.debuggingEnabled()) {
            String invokingClassName = ""; // <-- how do I get this?
            logger.debug("Executing {}", invokingClassName);
        }
        // shared application logic is here...
    }
}

public MyClass extends AbstractClass {
    public MyClass() {}

    @Override
    public void execute(ContextObject context) {
        super.execute(context);
        // application logic...
    }
}

I have worked with parsing stack traces before and I suspect that is the route I will have to go if I want this information. Does anyone know of a library that will do this for me or a good code snippet?

+8  A: 

Doesn't this.getClass().getName() do the trick? Namely:

public void execute(ContextObject context) {
    if (logger.debuggingEnabled()) {
        String invokingClassName = ""; // <-- how do I get this?
        logger.debug("Executing {}", this.getClass().getName());
    }
    // shared application logic is here...
}
cletus
Wow. Do I feel stupid. Why was I under the impression that getClass() would return the abstract class instance... Thank you.
Elijah
+4  A: 

Why do you want to log the class name explicitly. Log4j already do that. The way you have defined your Logger will do the trick. Check your log file.

Bhushan
+6  A: 

You've already got that information when you execute this line:

private Logger logger = LoggerFactory.getLogger(getClass());

That means you'll be logging with a category for the actual class. As that information is in the log already, I don't think it makes much sense to also include it in the execute method. Just make sure that your log output format includes the category name and it should be fine.

Jon Skeet