2

I have this parent abstract class which defines an Apache logger static object. Something like this:

import org.apache.log4j.Logger;

public abstract class A {

    private final static Logger logger;

        (...)

}

I know this code is illegal because the logger object is not initialized. The problem is I don't want to initialize it with logger = Logger.getLogger(A.class); because I want each child class to initialize it with its own class object, that way I will know which class caused which errors.

But at the same time I want to include some of my logging methods on the base class A.

What would be the best practice for this? Should I initialize it with A.class, then reinstantiate it for each child class? Somehow that feels incorrect to me.

2 Answers 2

2

Initialize it with the actual class it's created in:

logger = Logger.getLogger(getClass()); //log4j way of creating loggers

To do this you'll need to remove static modifier from your logger declaration. I prefer to keep it private and access it via a getter-method, but you can also make it protected and access directly from A subclasses.

You should not worry that many logger objects will be created, one logger per class instance: under the hood Logger contains a map of loggers, and every time you create a new logger - it's being cached. When you try to get logger for the same class the second time - it's just being retrieved from the inner map.

So, if you have 5 classes in your hierarchy - only 5 Logger objects will be created, no matter how many times you call getLogger(getClass()).

Sign up to request clarification or add additional context in comments.

3 Comments

I can't call getClass from a static scope. That's what my IDE says, anyway.
Thanks, I will do that then. But this applies to this specific case of Apache logger, and I'm curious as to how would one solve this for any other static object. How would you solve it then?
I would create the same kind factory object (like Logger), and produce new instance of object every time it's called. If for whatever needs (performance/stateless objects/etc) at some point I decide, that I don't want to create new objects any more - I will introduce caching inside the factory-object.
0

Should I initialize it with A.class, then reinstantiate it for each child object?

You should reinstantiate it for each child class.

1 Comment

sorry that's what I actually meant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.