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.
Initialize it with the actual class it’s created in:
To do this you’ll need to remove
staticmodifier from yourloggerdeclaration.I prefer to keep it
privateand access it via a getter-method, but you can also make itprotectedand access directly fromAsubclasses.You should not worry that many logger objects will be created, one logger per class instance: under the hood
Loggercontains 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
Loggerobjects will be created, no matter how many times you callgetLogger(getClass()).